Sub topic 11
Controlling media from JavaScript
This chapter assumes you can write basic HTML and CSS, select elements with querySelector, attach event listeners, and use promises with async/await. It also assumes you can already embed a <video> or <audio> element.
The HTMLMediaElement API
Both <audio> and <video> elements implement the HTMLMediaElement interface. This interface gives you methods, properties, and events for controlling playback from script. Everything in this chapter works on both element types.
The main members fall into three groups.
| Kind | Name | Purpose |
|---|---|---|
| Method | `play()` | Starts playback. Returns a promise. |
| Method | `pause()` | Pauses playback. |
| Method | `load()` | Resets the element and reloads its sources. |
| Property | `paused` | `true` when playback is not running. |
| Property | `currentTime` | Playback position in seconds. You can read and set it. |
| Property | `duration` | Length in seconds. It is `NaN` until metadata loads. |
| Property | `volume` | A number from 0 to 1. |
| Property | `muted` | `true` or `false`. |
| Property | `playbackRate` | Speed multiplier. `1` is normal speed. |
Setting currentTime seeks to that position. For example, video.currentTime = 30 jumps to the 30-second mark.
Play and pause with one button
The play() method returns a promise. It can reject if the browser blocks playback or the media fails to load. Always handle that rejection, as in this toggle button.
const video = document.querySelector('video');
const button = document.querySelector('#toggle');
button.addEventListener('click', async () => {
if (video.paused) {
try {
await video.play();
} catch (err) {
console.error('Playback was blocked or failed:', err.name);
}
} else {
video.pause();
}
});A common rejection is NotAllowedError. The browser raises it when autoplay rules apply and the user has not interacted with the page. Here the call runs inside a click handler, so the browser normally allows it.
Reacting to media events
The element fires events as its state changes. Listen for them instead of polling. Three are used most often:
loadedmetadatafires once the duration and dimensions are known.timeupdatefires repeatedly while the position changes.endedfires when playback reaches the end.
This example connects a <progress> element to a video.
const video = document.querySelector('video');
const progress = document.querySelector('#progress');
video.addEventListener('loadedmetadata', () => {
progress.max = video.duration;
});
video.addEventListener('timeupdate', () => {
progress.value = video.currentTime;
});
video.addEventListener('ended', () => {
console.log('Playback finished');
});Set progress.max inside loadedmetadata. Before that event, duration is NaN, so the bar would have no valid range.
Common mistakes
- Reading
durationtoo early and gettingNaN. - Calling
play()without handling the returned promise, which leaves rejections unhandled. - Updating the interface from
timeupdatealone and assuming it fires at a fixed rate. Browsers fire it a few times per second.
Exercise
Why must the code that sets a progress bar's max run inside a loadedmetadata listener, and what happens if you read video.duration immediately after the page loads?
Show answer
The duration is only known after the browser has loaded the file's metadata. Before that, video.duration is NaN, so a max set from it is invalid. Setting max in a loadedmetadata listener guarantees the real duration is available.