Using separate names for the videos is a bad approach to take.
As soon as you get tempted to use namea, nameb, namec as classnames, you’re using class names incorrectly. Classnames are supposed to let you apply the same classname to multiple items. Unique identifiers are what you use instead when only one of the name is allowed.
However, unique identifiers are frequently the wrong approach, and are a good indicator that there’s normally a better way to do things.
Remove video id’s
As a result, I’m going to remove the unique identifiers from the video sections:
<p><button id="loadplayer1">Load Player 1</button></p>
<!--<div data-id="M7lc1UVf-VE" id="video1"></div>-->
<div data-id="M7lc1UVf-VE"></div>
<p><button id="loadplayer2">Load Player 2</button></p>
<!--<div data-id="ylLzyHk54Z0" id="video2"></div>-->
<div data-id="ylLzyHk54Z0"></div>
Instead of using a unique identifier, we can get the next element after the button instead.
// document.querySelector("#loadplayer1").addEventListener("click", function () {
document.querySelector("#loadplayer1").addEventListener("click", function (evt) {
const wrapper = evt.target.parentNode;
videoPlayer.init(wrapper.nextElementSibling);
});});
// document.querySelector("#loadplayer2").addEventListener("click", function () {
document.querySelector("#loadplayer2").addEventListener("click", function (evt) {
const wrapper = evt.target.parentNode;
videoPlayer.init(wrapper.nextElementSibling);
});
Remove the button id’s
Instead of using an identifier on the button elements, which forces us to duplicate our code, we can use a class name and handle all of the button elements at the same time.
<!--<p><button id="loadplayer1">Load Player 1</button></p>-->
<p><button class="loadplayer">Load Player 1</button></p>
...
<!--<p><button id="loadplayer2">Load Player 2</button></p>-->
<p><button class="loadplayer">Load Player 1</button></p>
...
// document.querySelector("#loadplayer1").addEventListener("click", function (evt) {
// const wrapper = evt.target.parentNode;
// videoPlayer.init(wrapper.nextElementSibling);
// });
// document.querySelector("#loadplayer2").addEventListener("click", function () {
// videoPlayer.init(document.querySelector("#video2"));
// });
document.querySelectorAll(".loadplayer").forEach(function (button) {
button.addEventListener("click", function (evt) {
const wrapper = evt.target.parentNode;
videoPlayer.init(wrapper.nextElementSibling);
});
});
And now, we can individually load those youtube videos, without needing unique classes or unique identifiers.
A single classname for the button is all we need.
We’re on the right track here. We should have all that we now need to apply this technique to the grid of videos.