Spark Player, end to end.
A vanilla-JavaScript video player for progressive files, HLS and four embedded providers — with three switchable themes, paged playlists, chapters, sprite hover previews and automatic provider artwork. No framework, no runtime dependencies, one stylesheet and one generated script.
Quick start
Create a mount element, load two files, and pass a config object. That is the whole setup.
<!-- 1. Styles -->
<link rel="stylesheet" href="assets/css/spark-player.css">
<!-- 2. Mount point -->
<div id="player"></div>
<!-- 3. Player -->
<script src="assets/js/spark-player.js"></script>
<script>
const player = SparkPlayer.create('#player', {
playlist: [
{ src: 'assets/media/sintel-trailer.mp4', title: 'Sintel' },
{ src: 'https://vimeo.com/1084537', title: 'Big Buck Bunny' }
],
theme: 'glass',
autoplayNext: true
});
</script>
Serve the page over HTTP with npm run serve (a range-capable static server) or npx serve. Opening the file with file:// blocks HLS, sprite sheets and provider SDKs.
A single-source player works too: pass src (and optionally type) instead of
playlist. The playlist sidebar hides itself when there is only one item.
Global API
| Member | Type | Description |
|---|---|---|
SparkPlayer.create(target, options) | function | Accepts a selector or an element. Returns the player instance. |
SparkPlayer.version | string | Bundled version, e.g. 1.1.0. |
Options
Every option is optional. Defaults are tuned for a dark, glass-first page.
| Option | Default | Notes |
|---|---|---|
src | '' | Single video source. Ignored when playlist is present. |
type | 'auto' | auto, video, hls, youtube, vimeo, dailymotion, facebook. |
title | '' | Title for a single source. Falls back to the file name. |
poster | '' | Single-source poster. Playlist items carry their own. |
playlist | [] | Array of items — see Playlist schema. |
startIndex | 0 | Item to load first. |
autoplay | false | Browsers usually require muted: true for this to succeed. |
muted | false | Initial mute state. |
volume | 0.8 | 0–1. |
loop | false | Loop the current item. |
playbackRate | 1 | 0.25–3. |
startTime | 0 | Single-source resume point in seconds. |
theme | 'glass' | glass, neon or desert. See Themes. |
accent / accent2 | '' | Optional per-instance accent override on top of the theme. |
chapters | [] | Single-source chapter list. |
subtitles | [] | Single-source text tracks. |
thumbnails | '' | WebVTT sprite sheet for hover previews. |
playlistTitle | 'Up next' | Sidebar heading. |
playlistOpen | true | Sidebar starts open on desktop, closed below 980px. |
showTopBar | false | Show the title/theme bar over the video. Also toggleable from Settings; remembered per visitor. |
autoplayNext | true | Advance when an item ends. |
loopPlaylist | false | Wrap after the last item. |
hideDelay | 2600 | Idle milliseconds before the controls fade. |
keyboard | true | Keyboard shortcuts while the player has focus. |
persist | true | Remember volume, mute, rate, autoplay, top bar and theme in localStorage. |
autoMetadata | true | Fetch missing posters and runtimes. See below. |
readyTimeout | 18000 | Milliseconds before a slow source becomes a recoverable error. 0 disables. |
leadingSkip | 10 | Seconds for the skip-back/forward buttons. |
doubleClickFullscreen | true | Double-click the stage to toggle fullscreen. |
crossorigin | false | Adds crossorigin="anonymous" to native video. |
dailymotionPlayerId | '' | Required for Dailymotion. Create one in Dailymotion Studio. |
facebookAppId / facebookAccessToken | '' | Optional; improves Facebook embed reliability. A Graph token also enables automatic Facebook artwork and runtime lookup ahead of the public fallbacks. |
facebookThumbnailProxy | '' | Optional CORS relay for the public-page Facebook thumbnail. Use {url} for an encoded target or {rawurl} for the raw embed URL. Empty uses the built-in relays. |
hls | {} | Merged into the hls.js config object. |
youtube | {} | Merged into the YouTube IFrame player vars. |
onReady / onError | null | Convenience callbacks; on() is preferred for multiple listeners. |
Playlist schema
Each item is a plain object. Everything except src is optional.
{
src: 'assets/media/sintel-trailer.mp4', // required
type: 'video', // optional hint
title: 'Sintel — Blender Open Movie',
poster: 'assets/posters/sintel.png', // wins over auto-fetch
duration: 52, // seconds; wins over auto-fetch
startTime: 0,
thumbnails: 'assets/media/sintel-thumbnails.vtt',
subtitles: [
{ src: 'assets/media/sintel-en.vtt', label: 'English', srclang: 'en' }
],
chapters: [
{ start: 0, title: 'The hunt' },
{ start: 10, title: 'The old storyteller' }
]
}
poster— any image URL. When present it is never replaced by provider artwork.duration— seconds. When greater than zero it is never overwritten.thumbnails— a WebVTT file whose cue payloads point at sprite images with#xywh=fragments.chapters—startmay also be calledtimeorat. Entries are sorted for you.
Items without a poster get a deterministic gradient placeholder immediately, so the sidebar never shows empty boxes while metadata loads.
Themes
Three complete visual identities ship in one stylesheet. The frosted segmented switch in the top bar — next to the Chapters button — swaps them live; the top bar is hidden by default and can be enabled from the Settings sheet. Each option carries a two-colour swatch dot: teal/violet for Glass, cyan/magenta for Neon, amber/terracotta for Desert.
#05060f, cyan→magenta gradient border, pulsing play ring, monospace timecode, Space Grotesk.
// At init
const player = SparkPlayer.create('#player', { playlist, theme: 'desert' });
// At runtime
player.setTheme('neon');
player.on('themechange', ({ theme, label }) => {
console.log(theme, label); // 'neon', 'Neon'
});
The choice is written to localStorage under spark-player:prefs when
persist is on, so a visitor keeps their theme across pages. Set persist: false
to opt out, or theme at init to force a starting point for new visitors only.
Theme tokens
Themes are plain CSS custom properties on the .spk root, exposed via data-theme. Override them in your own stylesheet when the three built-ins are not enough:
| Variable | Role |
|---|---|
--spk-accent | Primary accent — progress start, active states, focus ring. |
--spk-accent-2 | Secondary accent — progress end, glows. |
--spk-grad-1 / -2 / -3 | Play button and solid-button gradient stops. |
--spk-progress-mid | Middle stop of the timeline gradient. |
--spk-ink | Text/icon colour drawn on accent-filled controls. |
--spk-text / --spk-muted / --spk-faint | Text ramp. |
--spk-glass / --spk-glass-strong | Surface fills for the bar, sheets and popups. |
--spk-stroke / --spk-stroke-soft | Hairline borders. |
--spk-radius | Stage and sidebar corner radius. |
/* Your own theme, layered on top of Neon */
.spk[data-theme="neon"] {
--spk-accent: #ff7a18;
--spk-accent-2: #ffd166;
}
Auto posters & runtimes
Spark fills in missing playlist artwork and durations before the visitor clicks anything. The rule is
simple and absolute: a demo-supplied poster or duration always wins.
Only gaps are requested, and only once per src. A partial cache entry is completed later
if another item with the same source still needs the missing field.
| Provider | Artwork | Runtime |
|---|---|---|
| YouTube | hqdefault CDN thumbnail (always present, 480×360) | Hidden 16:9 IFrame player reads getDuration() through the official API, one probe at a time and cached per video ID |
| Dailymotion | Public Data API thumbnail (1080p preferred) | Public Data API duration |
| Vimeo | oEmbed thumbnail (requested at 1280px) | oEmbed duration |
| oEmbed title only; thumbnail scraped from the public plugin page through a CORS relay, or Graph with a token | Hidden Facebook SDK plugin (getDuration()), or Graph length with a token | |
| MP4 / WebM | Gradient placeholder | Detached <video> metadata probe |
| HLS / M3U8 | Gradient placeholder | Playlist fetch; master playlists resolve to the first variant and #EXTINF values are summed |
Requests run one at a time with a small gap, so a 30-item playlist does not open 30 connections at once. YouTube probes are serialised behind a single hidden player and time-boxed to nine seconds, so an unembeddable video cannot stall the queue. Facebook probes wait for the SDK for at most 14 seconds. Any failure is silent: the placeholder stays and playback is never blocked. A runtime learned during playback is written back to that playlist card, so the list becomes more accurate as the visitor watches.
Facebook has no public artwork/runtime endpoint. Spark scrapes the public plugin page through the CORS relays built into the player; they are best-effort and can rate-limit. Set facebookThumbnailProxy to your own relay for production, or supply facebookAccessToken for Graph lookups. Set autoMetadata: false to make no requests at all.
Playlist pagination
A short playlist scrolls. A playlist with more than nine items pages instead, so the
sidebar stays a fixed, scannable height. At nine items or fewer the pager is not rendered — and it never
appears for single-source players. On desktop the rail is pinned to the stage's 16:9 height, so a long
playlist scrolls inside the sidebar instead of stretching the video frame; the pager and Previous/Next
controls stay docked at the bottom. Below 980px the sidebar lifts out of the stage into a fixed,
viewport-anchored glass sheet (capped at 74vh) that slides in from the right, so paging
stays usable on a phone. Tapping the dimmed stage or anywhere outside the sheet closes it, and the
pinned height is cleared.
| Viewport | Rows per page |
|---|---|
| > 980px | 8 |
| 561–980px | 6 |
| ≤ 560px | 4 |
The pager shows a compact page window (1 … 4 5 6 … 12), a range readout
(9–16 of 24) and prev/next arrows that disable at the ends. Loading an item from anywhere —
autoplay advance, goTo(), keyboard N — jumps to the page that contains it.
Resizing the window recalculates the page size and re-renders without losing the active item.
// Replace the whole playlist; pagination recalculates automatically
player.setPlaylist(nextItems, 0, { autoplay: false });
Providers
MP4 / WebM
Full custom control layer: seek, volume, rate, captions, PiP, fullscreen, poster and sprite previews. Quality selection appears when the item lists qualities; otherwise the browser decides.
HLS / M3U8
hls.js is loaded from assets/vendor/hls.min.js with a CDN fallback. Safari and iOS use native HLS. Adaptive levels are normalised into the quality menu as auto plus per-height entries.
YouTube
The IFrame API is loaded from YouTube. Playback, seeking, volume, rate and captions are proxied through the official SDK. YouTube removed programmatic quality selection in 2019 (setPlaybackQuality is a documented no-op), so the player works around it: it resizes the hidden embed to the requested resolution and scales it back down to the stage. YouTube chooses its stream from the iframe's own width, so 720p, 1080p and 4K now switch for real. YouTube still enforces a floor of roughly 480p in the embed and can lower the stream when bandwidth is insufficient; in that case the menu shows the requested level and the level actually playing, for example 1080p · playing 720p.
Vimeo
The Vimeo Player SDK is vendored at assets/vendor/vimeo-player.js. Quality values are passed through as the SDK reports them (never doubling a p suffix), and automatic selection is preserved. Text tracks are enabled with the correct track kind.
Dailymotion
Dailymotion requires a Player ID from Dailymotion Studio — pass it as
dailymotionPlayerId or the embed will not initialise. The SDK is always fetched from
https://geo.dailymotion.com/libs/player/{id}.js. Dailymotion does not permit self-hosting,
which is why it is the one dependency that cannot live in assets/vendor/.
Facebook's plugin keeps its own controls, but Spark uses the Embedded Video Player API. It embeds the official XFBML plugin, starts playback from its own poster overlay, reads the real duration (and writes it back to the playlist card) and follows play/pause/buffering events. Once playback begins the frame is handed to Facebook's native controls. Facebook may autoplay muted under browser autoplay rules; Spark restores its saved volume and mute state as soon as playback starts. Adding facebookAppId improves embed reliability. Public oEmbed returns a title but no artwork or runtime, so Spark scrapes the public plugin page through a CORS relay for the thumbnail and reads the runtime from the same SDK plugin. Set facebookThumbnailProxy to your own relay for production, or supply facebookAccessToken to use Graph lookups instead.
Provider artwork and runtimes are fetched from public oEmbed/metadata endpoints, which need CORS. If a proxy or strict CSP blocks them, the playlist falls back to placeholders and still plays.
Chapters
Chapters produce three things at once: tick marks on the timeline, a Chapters dropdown in the top bar, and an active row that tracks playback. Clicking a row seeks to that chapter.
chapters: [
{ start: 0, title: 'The hunt' },
{ start: 10, title: 'The old storyteller' },
{ start: 20, title: 'Firelight' }
]
Plain numbers are accepted as a shorthand (chapters: [0, 10, 20]) and get autogenerated titles. Entries are sorted by start time, so order in the array does not matter.
Sprite previews
Hover previews use the standard WebVTT thumbnail-sprite format: each cue spans a time range and its
payload is an image URL with an #xywh= fragment describing one cell.
WEBVTT
00:00:00.000 --> 00:00:05.220
../posters/sintel-sprite.jpg#xywh=0,0,160,90
00:00:05.220 --> 00:00:10.440
../posters/sintel-sprite.jpg#xywh=160,0,160,90
- Cue paths are resolved relative to the VTT file, not the page.
- The sprite is cropped at the preview's real rendered width, so a wider sidebar or a theme change cannot drift the crop.
- Fast pointer movement is race-safe: a late sprite load can never overwrite a newer hover position.
- Without a sprite sheet, the preview shows the item's poster.
Subtitles
Native files use <track> elements. Provider tracks are mapped to the same menu.
subtitles: [
{ src: 'assets/media/sintel-en.vtt', label: 'English (SDH)', srclang: 'en', default: true }
]
Toggle with the CC button, the C key, or player.toggleCaptions(). Headerless YouTube tracks are listed by language code.
Keyboard
Shortcuts are active while the player has focus. Modifier combinations are ignored so browser and OS shortcuts keep working, and shortcuts never fire while you are typing in a form field.
| Key | Action |
|---|---|
Space / K | Play / pause |
← / → | Seek 5 seconds |
J / L | Seek 10 seconds back / forward |
↑ / ↓ | Volume ±5% |
M | Mute / unmute |
F | Fullscreen |
C | Captions |
P | Picture-in-picture |
N | Next item |
Home / End | Start / end of the timeline |
0–9 | Jump to 0–90% |
Esc | Close menu, chapters or mobile sidebar |
API
All chainable mutators return the instance.
| Method | Description |
|---|---|
play() | Start or resume. Retries automatically after an error. |
pause() | Pause playback. |
toggle() | Play / pause, or replay when ended. |
seek(seconds) | Absolute seek. |
seekBy(delta) | Relative seek. |
goTo(index, autoplay) | Load a playlist index. autoplay defaults to true. |
next(userInitiated) | Next item, wrapping when loopPlaylist is on. |
previous(userInitiated) | Previous item. If playback is past three seconds it restarts the current item first — the familiar media-player behaviour. Wired to the “Previous” button under the playlist. |
setPlaylist(items, index, options) | Replace the playlist, reset pagination, prefetch the new metadata and load index. |
setVolume(0–1) | Set volume and unmute if necessary. |
setMuted(bool) / toggleMute() | Mute controls. |
setRate(rate) | Playback speed, 0.25–3. |
setQuality(value) | 'auto' or a provider-specific level. YouTube applies it best-effort; providers without quality control show an informational toast. |
setCaption(value) / toggleCaptions() | 'off' or a track value. |
setTheme('glass'|'neon'|'desert') | Change the visual theme, persist it and emit themechange. |
getState() | Snapshot of playback state plus index, item, items and playlistOpen. |
retry() | Reload the current item at its last position. |
toggleFullscreen() | Enter or exit fullscreen. |
requestPiP() | Picture-in-picture, when the source supports it. |
toast(message, kind) | Show the built-in glass toast. kind: info, warn. |
on(event, fn) / off(event, fn) | Listeners. off(event) removes all. |
destroy() | Tear down adapters, listeners and timers; removes the DOM. |
player
.setTheme('desert')
.setPlaylist(episodes, 3, { autoplay: true })
.setRate(1.25);
console.log(player.getState().theme); // 'desert'
Events
Register with player.on(name, handler), or listen on the mount element for
spark:name custom events. The handler receives (detail, player).
| Event | Detail |
|---|---|
ready | { index, item, duration, provider } |
started | First frame of the first play. |
timeupdate | { currentTime, duration }, throttled. |
play / pause / ended | Playback transitions. |
itemchange | { index, item } — emitted once per load. |
load | { index, item } — emitted once per load, after itemchange. |
playlistchange | { items, index } after setPlaylist(). |
themechange | { theme, label } |
volumechange / ratechange / loopchange | Settings changes. |
qualitychange / actualqualitychange | Selected and observed quality. |
captionschange / captiontracks | Caption selection and discovery. |
fullscreenchange / pipchange | Presentation changes. |
error | { code, message } — not_found, unsupported, format, playback, provider, timeout. |
destroy | Instance torn down. |
player.on('themechange', ({ label }) => {
document.body.dataset.playerTheme = label.toLowerCase();
});
document.querySelector('#player').addEventListener('spark:itemchange', (event) => {
document.title = event.detail.item.title;
});
Files & build
The shipped player is one file: assets/js/spark-player.js. It is assembled from the readable
fragments in build/, in filename order, by a small Node script.
spark_audio_player/
├── index.html // demo landing page
├── documentation.html // this page
├── README.md
├── package.json
├── build/ // source fragments, concatenated in order
│ ├── 01-core.js
│ ├── 02-media-adapter.js
│ ├── 03-youtube.js
│ ├── 04-iframes.js
│ ├── 05-player-core.js
│ ├── 06-state.js
│ ├── 07-ui.js
│ ├── 08-interaction.js
│ └── 09-api.js
├── tools/build.js // bundle builder
├── tools/serve.js // range-capable preview server
├── assets/css/spark-player.css
├── assets/js/spark-player.js // generated — do not edit
├── assets/js/demo.js
└── assets/vendor/ // hls.min.js, vimeo-player.js
| Command | What it does |
|---|---|
npm run build | Regenerate assets/js/spark-player.js from build/. |
npm run check | Exit non-zero if the bundle is stale — use it in CI or a pre-commit hook. |
npm run serve | Start the dependency-free range-capable preview server on localhost:8080. php -S does not support Range, so local MP4 seeking needs this server (or Apache/Nginx). |
Editing assets/js/spark-player.js directly is a dead end — the next build overwrites it. Change the matching file in build/ and run npm run build.
Troubleshooting
The player is blank or the sidebar has no artwork
- Open the page over HTTP, not
file://. - Check the console for a 404 on
assets/js/spark-player.js. - Provider artwork needs CORS; a strict CSP
img-srcorconnect-srcwill block it silently.
YouTube stays on “Loading”
- An ad blocker or privacy extension is usually blocking
youtube.com/iframe_api. - Some videos disable embedding. The error card links to open the video on YouTube directly.
Dailymotion shows an error card
dailymotionPlayerIdis missing or belongs to another domain.- Create a Player in Dailymotion Studio and whitelist your domain.
Hover preview is missing
- The item needs
thumbnailspointing at a valid WebVTT file. - Sprite cues must use
#xywh=x,y,w,hand the image must be reachable from the VTT's folder.
Runtimes show --:--
- The provider refused the metadata request (rate limit, CORS, private video).
- Supply
durationin the item to make it deterministic.
The pager never appears
- Pagination only activates above nine items. Below that the list scrolls, which is intentional.
Theme resets on reload
persistis off, orlocalStorageis blocked. Private windows often block it.
Autoplay is blocked
- Browsers require muted autoplay. Use
{ autoplay: true, muted: true }, or wait for a user gesture.