简体   繁体   中英

Pause Multiple HTML5 Videos

I have multiple HTML5 videos in a slider at http://ghostpool.com/wordpress/phideo and when I click on any of the slider buttons the first video is paused using the following onclick function.

<a href="#" onclick="pausePlayer();">LINK</a>


var htmlPlayer = document.getElementsByTagName('video')[0];

function pausePlayer() {
  htmlPlayer.pause();
}

However the second video does not pause when the slider buttons are clicked. I assume the Javascript above does not work with multiple videos?

EDIT: Additionally, if clicking on the video element itself I want to toggle a play and pause function. I"m using this code, but it plays and stops all videos at once. I assume I'm not looping it correctly:

function togglePlayer() {

for(var i = 0; i < htmlPlayer.length; i++){

    if ( htmlPlayer[i].paused || htmlPlayer[i].ended ) {    

        if ( htmlPlayer[i].ended ) { htmlPlayer[i].currentTime = 0; }
        htmlPlayer[i].play();

      }  else { 

      htmlPlayer[i].pause();

    }

}
}

This obviously won't work because you are only getting the first element in the array returned by getElementsByTagName . The [0] part accesses the first element in the array. What you would want to do is to iterate through all of them with a loop, like this:

var htmlPlayer = document.getElementsByTagName('video');

function pausePlayer() {
  for(var i = 0; i < htmlPlayer.length; i++){
    htmlPlayer[i].pause();
  }
}

Edit

Regarding your second question - You can try using this instead:

for(var i = 0; i < htmlPlayer.length; i++){
    htmlPlayer[i].onclick = function() {
        if ( this.paused || this.ended ) {    
            if ( this.ended ) { this.currentTime = 0; }
            this.play();
        }  else { 
            this.pause();
        }
    }
}

this in a event handler should refer to the element that called it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM