javascriptvideoaddeventlistenerfullscreenids

efficient way of creating an event listener for multiple IDs


here is a scirpt using which I am enabling full-screen mode when a video is played:

document.getElementById("qmedia").addEventListener("playing", event => {

    const player = document.getElementById("qmedia");
    if (player.requestFullscreen) 
        player.requestFullscreen();
    else if (player.webkitRequestFullscreen) 
        player.webkitRequestFullscreen();
    else if (player.msRequestFullScreen) 
      player.msRequestFullScreen();
})

The challenge here is I have multiple videos on my screen and I want to avoid copy-pasting the same script multiple times. Any suggestions for what could be an efficient method? There is also a class on my video .qmedia


Solution

  • Change the id to class, and itarete through all the elements to add the same eventlistener to each.

    const players = document.querySelectorAll(".qmedia")
    
    Array.from(players).forEach(
      player=>player.addEventListener("playing", event => {
        if (player.requestFullscreen) 
            player.requestFullscreen();
        else if (player.webkitRequestFullscreen) 
            player.webkitRequestFullscreen();
        else if (player.msRequestFullScreen) 
          player.msRequestFullScreen();
    }))
    <div class="qmedia">Click</div>
    <div class="qmedia">Click</div>
    <div class="qmedia">Click</div>
    <div class="qmedia">Click</div>
    <div class="qmedia">Click</div>