Sub topic 14
Building custom controls
This chapter shows how to replace the browser's built-in player controls with your own, using the HTMLMediaElement API, media events, and native form elements. It assumes you know the video element and its attributes, can add event listeners and use async/await, and have read the earlier chapters on the play() promise and media events.
When custom controls are worth it
The controls attribute gives you a player that is keyboard operable, translated, and tested across browsers. Build your own only when you need something it cannot do: a matching visual design, extra buttons such as playback speed, or a player that controls several media elements at once. Custom controls move the accessibility work to you, so the rest of the chapter treats that work as part of the build.
Use progressive enhancement. Leave controls in the markup, and let JavaScript remove it once your controls are ready. If the script fails to load, the visitor still gets the native player.
Start with native elements
Build the controls from button and input type="range". These elements are focusable, respond to Space, Enter, and arrow keys, and expose the correct roles to assistive technology. A div with a click handler gives you none of that.
<div class="player">
<video id="player" src="clip.mp4" preload="metadata" playsinline controls></video>
<div class="controls">
<button type="button" id="toggle">Play</button>
<input type="range" id="seek" min="0" max="0" step="0.1" value="0" aria-label="Seek">
<output id="time">0:00 / 0:00</output>
<button type="button" id="mute" aria-pressed="false">Mute</button>
<input type="range" id="volume" min="0" max="1" step="0.05" value="1" aria-label="Volume">
</div>
</div>The type="button" attribute stops the buttons from submitting a form if the player is ever placed inside one. The output element is a natural fit for text that changes as the video plays.
One direction of data flow
The most common bug in custom players is a UI that disagrees with the real playback state. It happens when a click handler flips a label and assumes the action worked. play() can be rejected, the video can stall, and the user can also pause from a keyboard media key, a headset button, or the operating system's media overlay. None of those go through your button.
Follow one rule: user actions call methods on the media element, and the UI changes only in response to media events.
The complete script
const video = document.querySelector('#player');
const toggle = document.querySelector('#toggle');
const seek = document.querySelector('#seek');
const time = document.querySelector('#time');
const mute = document.querySelector('#mute');
const volume = document.querySelector('#volume');
let scrubbing = false;
video.controls = false;
function format(seconds) {
if (!Number.isFinite(seconds)) return '0:00';
const m = Math.floor(seconds / 60);
const s = Math.floor(seconds % 60).toString().padStart(2, '0');
return `${m}:${s}`;
}
function updateTime() {
const now = format(video.currentTime);
const total = format(video.duration);
time.textContent = `${now} / ${total}`;
seek.setAttribute('aria-valuetext', `${now} of ${total}`);
if (!scrubbing) seek.value = video.currentTime;
}
toggle.addEventListener('click', async () => {
if (video.paused) {
try {
await video.play();
} catch (err) {
console.error('Playback was blocked or failed:', err.name);
}
} else {
video.pause();
}
});
video.addEventListener('play', () => { toggle.textContent = 'Pause'; });
video.addEventListener('pause', () => { toggle.textContent = 'Play'; });
video.addEventListener('ended', () => { toggle.textContent = 'Play'; });
video.addEventListener('loadedmetadata', () => {
seek.max = video.duration;
updateTime();
});
video.addEventListener('durationchange', () => {
if (Number.isFinite(video.duration)) seek.max = video.duration;
});
video.addEventListener('timeupdate', updateTime);
seek.addEventListener('pointerdown', () => { scrubbing = true; });
window.addEventListener('pointerup', () => { scrubbing = false; });
seek.addEventListener('input', () => {
video.currentTime = seek.valueAsNumber;
updateTime();
});
mute.addEventListener('click', () => { video.muted = !video.muted; });
volume.addEventListener('input', () => {
video.volume = volume.valueAsNumber;
video.muted = video.volume === 0;
});
video.addEventListener('volumechange', () => {
mute.setAttribute('aria-pressed', String(video.muted));
volume.value = video.muted ? 0 : video.volume;
});Design decisions in the script
Awaiting play()
The click handler awaits play() and catches rejection, as covered in the earlier chapter on the promise. The label does not change in the catch block. If playback fails, no play event fires, so the button correctly still says "Play".
Scrubbing without fighting the slider
While the user drags the seek slider, timeupdate keeps firing and would move the thumb back to the old position. The scrubbing flag stops updateTime from writing seek.value during a drag. The pointerup listener is on window because the pointer is often released outside the slider. Keyboard users never set the flag, so arrow keys work normally. Each arrow press fires input, which seeks.
Duration is not always a number
Before metadata loads, video.duration is NaN. For live streams it can be Infinity. The format function guards against both, and durationchange handles sources whose duration becomes known later. For a live stream, a seek bar makes no sense and you should hide it.
Labels and state
The play button changes its visible text. The mute button keeps a fixed label and uses aria-pressed, so a screen reader announces "Mute, toggle button, pressed". Use one technique per button. Changing the label and also toggling aria-pressed makes the state read out twice and confusingly.
Accessibility checklist
| Requirement | How to meet it |
|---|---|
| Reachable by keyboard | Use `button` and `input type="range"`, and keep them in a logical tab order |
| Visible focus | Do not remove outlines. If you restyle them, keep a high-contrast focus indicator |
| Names for every control | Visible text or `aria-label`. An icon-only button needs a text name |
| Current state announced | `aria-pressed` for toggles, `aria-valuetext` for sliders |
| Time readable | Use `aria-valuetext` such as "1:05 of 3:20", because a raw number of seconds is unhelpful |
| Captions still work | Custom controls need a captions toggle that sets a text track's `mode` to `"showing"` or `"hidden"` |
| Touch targets | Make buttons at least about 44 by 44 CSS pixels |
The captions row is easy to miss. The browser's own captions menu disappears with the native controls. To restore it, loop over video.textTracks and set mode on the chosen track. Also, do not make a click on the video itself the only way to play it. It is a fine shortcut, but it is not focusable by default.
Common mistakes
- Changing the button label inside the click handler instead of in the
playandpausehandlers. - Forgetting
playsinline, which makes iOS Safari take the video fullscreen on play. - Updating the DOM from
timeupdatemore than necessary. It fires only a few times per second, which is fine for text. For smooth animation, readcurrentTimeinrequestAnimationFramewhile playing. - Setting
currentTimebefore metadata has loaded. Some browsers ignore it or clamp it to zero. - Using only
volume = 0to silence audio. Usemuted, which remembers the previous volume.
Exercise
A user pauses your custom player with the keyboard media key on their laptop. The button label still says "Pause". Which event handler design caused this, and how do you fix it?
Show answer
The label was changed inside the button's click handler, so it only reflects clicks on that button. A media key calls pause on the element without going through the click. Fix it by updating the label in handlers for the video element's play and pause events (and ended), so the UI follows the real playback state.
Exercise
While a user drags the seek slider, the thumb jumps back to the current playback position every few hundred milliseconds. Why does this happen, and what does the script above do to prevent it?
Show answer
The timeupdate handler writes video.currentTime into the slider's value several times per second, overriding the drag position. The script sets a scrubbing flag on pointerdown, clears it on pointerup, and skips updating seek.value while the flag is true.