-2

The click event is only working on the first div i.e div with id video1, due to some reason it is not working when I click div with id video2 and video3. I am not able to understand the problem in the code.

<header class="head">
            VIDEO PLAYER
        </header>


        <div id="videos">
            <div id="video1">
                <video class="video1" >
                    <source src="https://www.videvo.net/videvo_files/converted/2018_04/preview/180301_06_A_CityRoam_03.mp420186.webm">
                </video>
            </div>

            <div id="video2">
                <video class="video2">
                    <source src= "https://www.videvo.net/videvo_files/converted/2016_01/preview/Forest_15_2_Videvo.mov92730.webm">
                </video>
            </div>

            <div id="video3">
                <video class="video3">
                    <source src="https://www.videvo.net/videvo_files/converted/2016_09/preview/160820_125_NYC_OutOfFocusCarLights5_1080p.mp444096.webm">
                </video>
            </div>
        </div>
window.onload=  init;

function init(){
    var frame1=document.querySelector('#video1');

    frame1.innerHTML+= ' <br> <button id="play">play </button> <button id="pause">pause</button> <button id="volume-up">volume up</button> <button id="volume down">volume-down</button> <button id="mute">mute</button>  ';

}


//to play another video
var click= document.querySelector('#videos > div');

click.addEventListener('click', nextPlaylist);

function nextPlaylist(evt){

    console.log('it worked');
}
  • 1
    `querySelector` returns at most _one_ element, you need `querySelectorAll` there. And then you need to _loop over_ the list of nodes that returns, and call addEventListener on each one of them individually. – CBroe Jun 03 '20 at 14:03
  • 1
    Or is you ever use jQuery: `$('#videos > div'').on('click', nextPlaylist)` – Justinas Jun 03 '20 at 14:05

1 Answers1

0

Thats because you are only selecting the first element and setting that

const clicks = document.querySelectorAll("#videos > div");

//nodelists are not arrays so you can't do a standard for index loop
//I believe for const works fine but just to make sure i added deconstructing to an array
//forEach also works but how you loop through nodelists are another topic you can research
for(const click of [...clicks]) {
  click.addEventListener("click", nextPlaylist);
}