What is the HTML5 Video API and how do you control playback with JavaScript?
· Category: HTML & CSS
Short answer
HTML5 <video> elements implement the HTMLMediaElement interface, exposing methods like play(), pause(), and properties like currentTime and volume for full programmatic control.
How it works
JavaScript can interact with a video element directly. Common tasks include custom play/pause buttons, progress bars, and syncing captions.
Example
<video id="vid" src="movie.mp4" preload="metadata"></video>
<button id="play">Play</button>
<button id="skip">Skip 10s</button>
<script>
const vid = document.getElementById('vid');
document.getElementById('play').addEventListener('click', () => {
vid.paused ? vid.play() : vid.pause();
});
document.getElementById('skip').addEventListener('click', () => {
vid.currentTime += 10;
});
vid.addEventListener('timeupdate', () => {
console.log(vid.currentTime);
});
</script>
Tips
- Always respect the
autoplaypolicy; many browsers block sound without user interaction. - Use the
canplayorloadedmetadataevents before querying duration or dimensions. - For streaming, consider the Media Source Extensions API (MSE).