How to get JS to execute for whole class?

248 views Asked by At

I have many videos on my page and I've created and extra button on the video to speed up video, and it is working if I call getElementById. Is it possible to use one Javascript for all videos on the page? Since it's around 80+, then would be lots of duplicated javascript code, as I also have to make button to go back to speed 1x

HTML page block looks like this.

....
<div class="LigthBox">
        <a href="#DVDList" class="close" id="clVid1"></a> <a href="javascript:Play15();" class="speed15"> <a href="javascript:Play1();" class="speed1"></a> 
        <video class="Video_LitBox" id="DVD101" controls preload="none" poster="img/DVDThb-101.png"> <source src="res/vid-str.php?play_video=101" type="video/mp4"> </video>  
        <h3 class="DVid_title">101 Intro </h3>
        <p class="DVid_body">101 Intro description .....</p>
    </div>
....

and below in script area I have the following:

<script type="application/javascript">
  var vid = document.getElementById("DVD101");
  vid.onended = function() { 
    alert("The video has ended");
    fireEvent( document.getElementById('clVid1'), 'click'); 
  } 

  function Play1() { 
    vid.playbackRate = 1;
  }
  function Play15() { 
    vid.playbackRate = 1.5;
  }
</script>

so variable vid to be somehow defined for every video on the page or any other work around if any. btw fireevent also doesn't work after video finishes, alert shows but doesn't close the the window.

2

There are 2 answers

0
DenisZ On BEST ANSWER

For anyone interested in solution. Thanks to @Aaron_Actu suggestion and some digging I ended up making just one short JS with argument (video-speed)

so call from html looks the same for all videos

....
<a href="javascript:PlaySpeed(15);" class="speed15"></a>
....

and at the bottom of the page script looks like

....
  function PlaySpeed(vspd) { 
    var vid = document.querySelectorAll('video');
    for (var i=0; i<vid.length; i++) {     
      vid[i].playbackRate = vspd / 10;
    }
  }
...

I pass "video-speed" with 10x multiplier so that argument is an integer

4
Aaron_Actu On

You should maybe change the selector, instead of using getElementById() method you should try :

document.querySelectorAll('video')

which will return an array with all video instances. Then, you can easily do whatever you want with a simple for...in or forEach loop.

More details about querySelectorAll() method.