Sub topic 13
Reacting to media events
This chapter assumes you can select elements and attach listeners in JavaScript. It also assumes you know what play() returns and the basics of the <audio> and <video> elements from earlier chapters. Here you will learn which events a media element fires, in what order, and how to use them to build progress bars, loading indicators, and error messages.
How media events work
Every <audio> and <video> element is an HTMLMediaElement. It fires events as it loads data, starts and stops playing, seeks, or fails. You subscribe with addEventListener, the same way as for clicks.
Three properties of media events cause most bugs:
- They do not bubble. A listener on a wrapper
<div>will not hear aplayevent from the video inside it. Attach listeners to the media element itself, or use the capture phase ({ capture: true }) on an ancestor. - They are not replayed. If an event fired before your script attached a listener, you will never see it. Check the element's state properties first.
- Many events are hints about state, not guarantees. Always read the current state from properties such as
paused,readyState, andcurrentTimeinstead of tracking it only from events.
The loading sequence
When a source is set, the browser works through a predictable series of events.
The events that matter most:
| Event | Meaning | Typical use |
|---|---|---|
| `loadstart` | The browser began fetching the resource. | Show a loading state. |
| `loadedmetadata` | Duration and video dimensions are known. | Set a progress bar's maximum. |
| `loadeddata` | The frame at the current position is available. | Hide a placeholder. |
| `canplay` | Enough data to start, but it may stall later. | Enable a Play button. |
| `canplaythrough` | The browser estimates it can play to the end without stalling. | Rarely needed. |
| `progress` | More data was downloaded. | Redraw a buffer indicator. |
| `error` | Loading or decoding failed. | Show an error message. |
The play event fires when playback is requested, and playing fires when frames are actually advancing. The distinction matters: after play, the element may still be waiting for data. waiting fires when playback stops because the next frame is not available, and playing fires again when it resumes. A loading spinner should therefore appear on waiting and disappear on playing.
Reading state with readyState
Because events are not replayed, use readyState to learn how far loading has progressed.
| Value | Constant | Meaning |
|---|---|---|
| 0 | `HAVE_NOTHING` | No information yet. |
| 1 | `HAVE_METADATA` | Duration and dimensions known. |
| 2 | `HAVE_CURRENT_DATA` | Current frame available, not the next. |
| 3 | `HAVE_FUTURE_DATA` | Current and some following data available. |
| 4 | `HAVE_ENOUGH_DATA` | Playback should continue without stalling. |
A helper that works whether the event has already fired or not:
function whenMetadataReady(media) {
return new Promise((resolve) => {
if (media.readyState >= HTMLMediaElement.HAVE_METADATA) {
resolve();
} else {
media.addEventListener('loadedmetadata', () => resolve(), { once: true });
}
});
}
const video = document.querySelector('video');
await whenMetadataReady(video);
console.log('Duration in seconds:', video.duration);The top-level await requires the script to be loaded as <script type="module">. Outside a module, wrap the call in an async function.
A progress bar that handles edge cases
The basic pattern sets max on loadedmetadata and updates value on timeupdate. Two edge cases matter. duration is NaN before metadata loads, and it is Infinity for live streams. The durationchange event also fires whenever the value changes, so listen for it instead of relying on loadedmetadata alone.
<video controls src="clip.mp4"></video>
<progress id="progress" value="0" max="1"></progress>
<span id="time">0:00</span>
<script type="module">
const video = document.querySelector('video');
const progress = document.querySelector('#progress');
const time = document.querySelector('#time');
function format(seconds) {
const m = Math.floor(seconds / 60);
const s = Math.floor(seconds % 60).toString().padStart(2, '0');
return `${m}:${s}`;
}
function syncDuration() {
if (Number.isFinite(video.duration)) {
progress.max = video.duration;
}
}
video.addEventListener('durationchange', syncDuration);
video.addEventListener('loadedmetadata', syncDuration);
video.addEventListener('timeupdate', () => {
progress.value = video.currentTime;
time.textContent = format(video.currentTime);
});
syncDuration();
</script>The final syncDuration() call covers the case where metadata loaded before the script ran.
The timeupdate event fires only a few times per second, and the exact rate is up to the browser. That is fine for text and coarse bars. For a smooth scrubber, read video.currentTime inside a requestAnimationFrame loop that runs while the video is playing.
Showing a buffering indicator
const video = document.querySelector('video');
const spinner = document.querySelector('#spinner');
video.addEventListener('waiting', () => {
spinner.hidden = false;
});
for (const type of ['playing', 'pause', 'ended', 'error']) {
video.addEventListener(type, () => {
spinner.hidden = true;
});
}Hiding the spinner on pause, ended, and error as well prevents it from staying visible after playback stops for another reason.
Handling errors
When a load or decode fails, the element fires error, and video.error holds a MediaError object with a numeric code.
| Code | Constant | Typical cause |
|---|---|---|
| 1 | `MEDIA_ERR_ABORTED` | The user or script cancelled the fetch. |
| 2 | `MEDIA_ERR_NETWORK` | A network failure after loading began. |
| 3 | `MEDIA_ERR_DECODE` | The file is corrupt or uses unsupported features. |
| 4 | `MEDIA_ERR_SRC_NOT_SUPPORTED` | A bad URL, a wrong MIME type, or an unsupported format. |
const video = document.querySelector('video');
const message = document.querySelector('#message');
video.addEventListener('error', () => {
const err = video.error;
if (!err) return;
const reasons = {
[MediaError.MEDIA_ERR_ABORTED]: 'Playback was cancelled.',
[MediaError.MEDIA_ERR_NETWORK]: 'A network error interrupted the download.',
[MediaError.MEDIA_ERR_DECODE]: 'The file could not be decoded.',
[MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED]: 'This format or address is not supported.',
};
message.textContent = reasons[err.code] ?? 'Unknown media error.';
});Errors on source elements
If you use <source> children, a failure to load one source fires error on that <source> element, not on the media element. The event does not bubble. Capture it on the parent:
const video = document.querySelector('video');
video.addEventListener(
'error',
(event) => {
if (event.target instanceof HTMLSourceElement) {
console.warn('Source failed:', event.target.src);
}
},
{ capture: true }
);The browser then tries the next <source>. The media element's own error event fires only after every source has failed.
Seeking, volume, and rate
Several events report changes you or the user cause:
seekingfires when a seek starts, andseekedfires when it finishes. During a seek,video.seekingistrue.volumechangefires for changes tovolumeormuted.ratechangefires whenplaybackRatechanges.endedfires when playback reaches the end. It does not fire ifloopis set.
When ended fires, currentTime equals duration and paused is usually true. Calling play() afterwards restarts from the beginning.
Common mistakes
- Using
canplaythroughto start playback automatically. Browsers may fire it late or never when the connection is slow. Prefercanplay. - Updating the DOM on every
progressevent. It can fire often. Readvideo.bufferedand redraw only when needed. - Assuming
playmeans the video is moving. Useplaying. - Registering a listener after the element has loaded and waiting forever. Check
readyStatefirst. - Forgetting to remove listeners on elements you discard. Use the
{ once: true }option or anAbortControllersignal.
Exercise
A page attaches a loadedmetadata listener at the bottom of the body, but the progress bar's maximum is never set on some page loads, even though the video plays. What is the likely cause, and how do you fix it?
Show answer
The video's metadata sometimes loads, and the event fires, before the script attaches its listener. Media events are not replayed. Fix it by checking video.readyState >= HTMLMediaElement.HAVE_METADATA when the script runs and setting progress.max immediately if so. Also listen for durationchange so later changes are handled.
Exercise
You wrap a <video> with two <source> children in a <div> and add an error listener to the <div>. It never runs when the first source fails to load. Why, and what are two ways to catch it?
Show answer
The error event fires on the failing <source> element and does not bubble, so the <div> listener never sees it. Either add the listener to the <div> with { capture: true }, or attach a listener directly to each <source> element.