We’re learned how to listen out for a selection of media playback events, but let’s take a quick look at ways to programmatically interact with video playback, as well as extend our knowledge by thinking about ways to give the user some kind of visual feedback regarding playback progress.
<aside> <img src="/icons/light-bulb_blue.svg" alt="/icons/light-bulb_blue.svg" width="40px" />
When you give your <video> element the controls attribute, each browser has its own unique styling for the playback controls UI. Instead of using the defaults, you could instead design your own user interface for how the viewer could interact with playback.
</aside>
play() and pause()Imagine we’ve got a <video> element on our page, as well as two <button> elements, each with unique IDs:
<video id="bunny" src="<https://media.w3.org/2010/05/bunny/movie.mp4>"></video>
<button id="play">Play</button>
<button id="pause">Pause</button>
The <video> element here lacks a controls attribute, but with jQuery, we can listen out for clicks on the <button> elements and use that to trigger play()/pause() events on the video.
$('#play').click(function() {
$('#bunny').get(0).play();
};
$('#pause').click(function() {
$('#bunny').get(0).pause();
};
To update a progress bar based on video playback, you can listen to the timeupdate event on the <video> element and calculate the current progress as a normalised fractional value (ranging from 0–1), or as percentage (ranging from 0%–100%) depending on your tastes. Let’s start out by looking at the <progress> element.
<aside> <img src="/icons/code_lightgray.svg" alt="/icons/code_lightgray.svg" width="40px" />
To simplify this example, we’ll temporarily include the controls attribute to give us the browser’s default playback controls, so that we can focus on the idea of updating another element.
</aside>
<progress>Let’s refactor our code to group the <video> element with a <progress> element.
<div id="videoContainer">
<video id="bunny" src="<https://media.w3.org/2010/05/bunny/movie.mp4>" controls></video>
<progress id="progress" max="1" value=""></progress>
</div>