ADRIAN
ADRIAN

Reputation: 109

custom html5 video controls jquery

I have found the following code to add custom html5 video controls.

html:

    <div>
<video id="video" controls>
   <source src="/images/videos/LargeRoom.mp4" type="video/mp4">
   <source src="grass-in-the-wind-sma.webm" type="video/webm">
</video>

<div id="controls">
<button id="playpause" title="play" onclick="togglePlayPause()">Play</button>
</div>

</div>


<div>
<video id="video" controls>
   <source src="/images/videos/LargeRoom.mp4" type="video/mp4">
   <source src="grass-in-the-wind-sma.webm" type="video/webm">
</video>

<div id="controls">
<button id="playpause" title="play" onclick="togglePlayPause()">Play</button>
</div>

</div>

and the following javascript:

   // Grab a handle to the video
   var video = document.getElementById("video");
   // Turn off the default controls
   video.controls = false;


   function togglePlayPause() {
   var playpause = document.getElementById("playpause");
   if (video.paused || video.ended) {
      playpause.title = "pause";
      playpause.innerHTML = "pause";
      video.play();
   }
   else {
      playpause.title = "play";
      playpause.innerHTML = "play";
      video.pause();
   }
}

video.addEventListener('play', function() {
   var playpause = document.getElementById("playpause");
   playpause.title = "pause";
   playpause.innerHTML = "pause";
}, false);
video.addEventListener('pause', function() {
   var playpause = document.getElementById("playpause");
   playpause.title = "play";
   playpause.innerHTML = "play";
}, false);

The issue I am having is that both play/stop buttons control the top first video. As oppose to each controlling their own video.

Upvotes: 1

Views: 1880

Answers (1)

pedromendessk
pedromendessk

Reputation: 3646

The IDs of the elements in the DOM must be unique. You should try to call your methods by the class names like this:

// Grab a handle to the video
var video = document.getElementsByClassName("video");

And here is a Fiddle with your code running properly only using javascript. Although I think the code would be much simple and clean if you used jQuery.

Hope it helped.

Upvotes: 2

Related Questions