Brennan
Brennan

Reputation: 73

How do I use Javascript to toggle play/pause for multiple videos when I click on the video?

When I add onclick="playPause()" to just one video it works great. I click the video and it'll play or pause just like I want it to. If I have more than one video, even if the videos have different IDs (for example: video id="v1" and video id="v2") whenever I click on one video it'll always play one specific video. Using this script on multiple videos seems to only allow play/pause toggling on one video. Here's the html and script I'm using:

<video id="v1" width="480px" height="267px" controls onclick="playPause()">
<source src="S12E13%203%20Acts%20of%20God.mp4" type="video/mp4">
</video>
    <script> 
var myVideo = document.getElementById("v1"); 
function playPause() { 
if (myVideo.paused) 
    myVideo.play(); 
else 
    myVideo.pause(); } 
    </script>


<video id="v2" width="480px" height="267px" controls onclick="playPause()">
<source src="S12E13%203%20Acts%20of%20God.mp4" type="video/mp4">
</video>
    <script> 
var myVideo = document.getElementById("v2"); 
function playPause() { 
if (myVideo.paused) 
    myVideo.play(); 
else 
    myVideo.pause(); } 
    </script>


<video id="v3" width="480px" height="267px" controls onclick="playPause()">
<source src="S12E13%203%20Acts%20of%20God.mp4" type="video/mp4">
</video>
    <script> 
var myVideo = document.getElementById("v3"); 
function playPause() { 
if (myVideo.paused) 
    myVideo.play(); 
else 
    myVideo.pause(); } 
    </script>

BTW: not a big deal, but I've noticed the original Play button doesn't work anymore when I use this script. Is there a way to fix that?

Upvotes: 5

Views: 16149

Answers (1)

T J
T J

Reputation: 43156

You can pass the clicked element as an argument to the function like onclick="playPause(this)", then you just have a single definition:

function playPause (video) {
  if (video.paused) 
    video.play(); 
  else 
    video.pause();
}

Or alternatively you can find all videos and bind event listeners to them iteratively using document.getElementsByTagName() or document.querySelectorAll():

document.querySelectorAll('video').forEach((video) => {
   video.addEventListener('click', function (event) {
     if (this.paused) 
       this.play(); 
     else 
       this.pause();
   });
});

Upvotes: 7

Related Questions