Html5 video is much like a img element in a html page. This means we can target the video element and its various components using JavaScript and we can even style the video element with CSS.
Lets create a custom control for video element. Our controls have three components:
■ play/pause button
■ timer that counts forward from zero
■ mute/unmute button
The different parts of the video controls:
<div id="controls" class="hidden">
<a id="playPause">Play/Pause</a>
<span id="timer">00:00</span>
<a id="muteUnmute">Mute/Unmute</a>
</div>
Media elements api
var videoEl = $('video')[0],
playPauseBtn = $('#playPause'),
vidControls = $('#controls'),
muteBtn = $('#muteUnmute'),
timeHolder = $('#timer');
videoEl.removeAttribute("controls");
The next step is to make our own custom controls visible. As mentioned earlier, we’ve used CSS to remove our controls from view by default. By using JavaScript to enable the visibility of the custom controls, we ensure that the user will never see two sets of controls.
videoEl.addEventListener('canplaythrough', function() {
vidControls.removeClass("hidden");
}, false)
Playing and Pausing the Video
playPauseBtn.bind('click', function() {
if (videoEl.paused) {
videoEl.play();
} else {
videoEl.pause();
}
});
videoEl.addEventListener('play', function() {
playPauseBtn.addClass("playing");
}, false);
videoEl.addEventListener('pause', function() {
playPauseBtn.removeClass("playing");
}, false);
Note
Disabling the Context Menu the video element’s context menu has an option for Save video as…. There’s been discussion online about how easy it is to save
HTML5 video, and this could affect how copyrighted videos will be distributed.
Muting and Unmuting the Video’s Audio Track
muteBtn.bind('click', function() {
if (videoEl.muted) {
videoEl.muted = false;
} else {
videoEl.muted = true;
}
});
videoEl.addEventListener('volumechange', function() {
if (videoEl.muted) {
muteBtn.addClass("muted");
} else {
muteBtn.removeClass("muted");
}
}, false);
Responding When the Video Ends Playback
videoEl.addEventListener('ended', function() {
videoEl.currentTime = 0;
videoEl.pause();
}, false);
Updating the Time as the Video Plays
videoEl.addEventListener('timeupdate', function() {
timeHolder[0].innerHTML = secondsToTime(videoEl.currentTime);
}, false);