Sub topic 11
Controlling media from JavaScript
This chapter assumes you know basic HTML attributes, how to select elements and attach event listeners in JavaScript, and how promises and async/await work. It covers the HTMLMediaElement API, which is the set of properties, methods, and events that <audio> and <video> elements share. You can use it to build your own play buttons, progress bars, and playback logic.
The working model
Both <audio> and <video> are HTMLMediaElement objects. Video adds extras such as videoWidth and videoHeight. Everything in this chapter works on both.
A media element has a state that changes over time, and it tells you about changes through events. The usual pattern has three steps:
- Read state from properties such as
paused,currentTime, andduration. - Change state by setting a property or calling a method such as
play(),pause(), orload(). - Listen for events to learn when the state actually changed.
The element works asynchronously. Setting a property or calling a method asks the browser to do something, and the browser may need time to finish. Your code should not assume the change has already happened.
Core properties
These properties cover most real-world needs.
| Property | Type | Writable | Meaning |
|---|---|---|---|
| `paused` | boolean | No | `true` when playback is not running |
| `ended` | boolean | No | `true` when playback reached the end |
| `currentTime` | number (seconds) | Yes | Current playback position. Setting it seeks. |
| `duration` | number (seconds) | No | Length of the media. `NaN` before metadata loads. |
| `volume` | number 0 to 1 | Yes | Audio level |
| `muted` | boolean | Yes | Silences output without changing `volume` |
| `playbackRate` | number | Yes | Speed. `1` is normal, `2` is double speed. |
| `readyState` | number 0 to 4 | No | How much data is available |
| `networkState` | number 0 to 3 | No | Whether the element is idle, loading, or has no source |
| `error` | `MediaError` or `null` | No | Details of the last failure |
Three details trip people up:
durationisNaNuntil theloadedmetadataevent fires. Live streams reportInfinity.volumeandmutedare independent. A muted element keeps itsvolumevalue, so unmuting restores the old level.- The
pausedproperty istruebefore playback starts, and also after anendedevent for non-looping media in some states. Do not use it as a "has the user started yet" flag.
Methods
play()starts or resumes playback. It returns a promise.pause()stops playback. It does not reset the position.load()resets the element and restarts the source selection process. You need it after changing<source>children dynamically. Changing thesrcproperty starts loading on its own.canPlayType(type)reports likely format support. A later chapter covers it.
There is no stop() method. To stop and rewind, call pause() and then set currentTime = 0.
Handling the play() promise
play() returns a promise. It resolves when playback has started. It rejects when playback cannot start, and the most common reason is the browser's autoplay policy, which blocks playback not triggered by a user gesture. The rejection is a DOMException, and its name tells you the cause:
| Error name | Typical cause |
|---|---|
| `NotAllowedError` | Autoplay policy blocked playback, or the user denied permission |
| `NotSupportedError` | The source is missing or in an unsupported format |
| `AbortError` | A `pause()` call or a new `load()` interrupted the start |
If you do not handle the rejection, the browser logs an "Uncaught (in promise)" error and your interface may be left showing the wrong state. Always handle it.
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();
}
});An AbortError is often harmless. It happens when a user clicks play and then pause quickly, and the pause interrupts the pending start. You can ignore it, but treat NotAllowedError and NotSupportedError as real conditions that need a visible message or a fallback.
Reacting to media events
The element dispatches events as its state changes. These are the ones you will use most.
| Event | Fires when |
|---|---|
| `loadedmetadata` | `duration` and dimensions are known |
| `canplay` | Enough data exists to start, though buffering may still stall it |
| `play` | Playback was requested or resumed |
| `playing` | Playback is actually running |
| `pause` | Playback was paused |
| `timeupdate` | `currentTime` changed during playback |
| `seeking` and `seeked` | A seek started and finished |
| `waiting` | Playback stopped to wait for more data |
| `ended` | Playback reached the end |
| `volumechange` | `volume` or `muted` changed |
| `error` | Loading or decoding failed |
The difference between play and playing matters. play fires when playback is requested. playing fires when frames or samples are really advancing. If the network stalls, you see waiting between them, and a spinner should follow waiting and hide on playing.
This example reads the duration once it is known, then updates a progress element as time passes.
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');
});timeupdate fires roughly every 250 ms, and the exact rate depends on the browser. That is fine for a progress bar and too coarse for frame-accurate work. For smooth animation, read currentTime inside requestAnimationFrame. For video, requestVideoFrameCallback is available in many browsers.
Seeking, ranges, and buffering
Setting currentTime asks the browser to jump. It only works smoothly if the server supports range requests, which a later chapter covers. Without them, some browsers cannot seek past the buffered part of a file.
Three properties describe what is available. Each returns a TimeRanges object with a length, plus start(i) and end(i) methods.
bufferedis what has been downloaded.playedis what the user has watched.seekableis where you may jump.
const media = document.querySelector('video');
media.addEventListener('progress', () => {
const ranges = media.buffered;
if (ranges.length > 0) {
const end = ranges.end(ranges.length - 1);
console.log(`Buffered up to ${end.toFixed(1)} s`);
}
});Buffered data can come in several separate ranges, for example after the user seeks ahead. Check length before reading, and do not assume range 0 covers the current position.
Building basic custom controls
You can hide the built-in controls by removing the controls attribute, then supply your own. Use real <button> elements, because they are keyboard operable and announced by screen readers without extra work.
<video id="player" src="clip.mp4" preload="metadata"></video>
<button id="play" type="button" aria-pressed="false">Play</button>
<input id="seek" type="range" min="0" max="0" value="0" step="0.1" aria-label="Seek">
<button id="mute" type="button" aria-pressed="false">Mute</button>
<script>
const video = document.querySelector('#player');
const play = document.querySelector('#play');
const seek = document.querySelector('#seek');
const mute = document.querySelector('#mute');
play.addEventListener('click', async () => {
if (video.paused) {
try {
await video.play();
} catch (err) {
console.error('Could not play:', err.name);
}
} else {
video.pause();
}
});
video.addEventListener('play', () => {
play.textContent = 'Pause';
play.setAttribute('aria-pressed', 'true');
});
video.addEventListener('pause', () => {
play.textContent = 'Play';
play.setAttribute('aria-pressed', 'false');
});
video.addEventListener('loadedmetadata', () => {
seek.max = video.duration;
});
video.addEventListener('timeupdate', () => {
seek.value = video.currentTime;
});
seek.addEventListener('input', () => {
video.currentTime = Number(seek.value);
});
mute.addEventListener('click', () => {
video.muted = !video.muted;
});
video.addEventListener('volumechange', () => {
mute.textContent = video.muted ? 'Unmute' : 'Mute';
mute.setAttribute('aria-pressed', String(video.muted));
});
</script>Keep these points in mind when you replace the native controls:
- Use
<input type="range">for seeking, with anaria-label, so arrow keys work. - Reflect state in the DOM, not only in color or icon shape.
- Keep captions reachable. Custom controls do not automatically include a captions menu, so you must build one with the
textTracksAPI or leave the native controls on.
Common errors
- Reading
durationtoo early and gettingNaN. Wait forloadedmetadata. - Calling
play()without handling the rejected promise. - Changing
<source>elements and forgetting to callload(). - Setting
currentTimebefore metadata loads. Some browsers ignore it, so set it inside aloadedmetadatalistener. - Assuming
timeupdateis frame-accurate. - Updating UI from your own click handlers instead of from media events.
- Using
<div>elements as buttons, which breaks keyboard and screen reader access.
Exercise
A user clicks your custom play button. video.play() rejects with a NotAllowedError, yet your button already says "Pause". Which change fixes the mismatch, and where should the button label be updated?
Show answer
Update the label from the play and pause event listeners, not from the click handler. Wrap await video.play() in a try/catch and show a message for NotAllowedError. The label then changes only when the element actually starts playing, so a rejected promise leaves it as "Play".
Exercise
Your progress bar sets progress.max = video.duration right after the script runs, and the bar never moves. Why, and what is the fix?
Show answer
duration is NaN until metadata loads, so max is invalid. Set progress.max inside a loadedmetadata listener.