Spark Player docs
API Reference · v1.1.0

Spark Player documentation

The complete reference for Spark Player — a dependency-free HTML5 video player with a smart, paginated playlist. Covers every option, method, event and CSS variable, plus integration recipes for vanilla JS, React, Vue and WordPress.

0runtime dependencies
6built-in themes
27typed events
7source families
11locales shipped

Overview

What Spark Player is, and how it is put together.

Spark Player is a single lightweight player that normalises every supported source family behind one consistent interface and one set of controls. You give it a playlist of items; it detects each source kind, mounts the right adapter, renders the controls and playlist, and emits typed events as playback proceeds.

Engine

The SparkPlayer class owns DOM structure, state, i18n and the adapter lifecycle. It implements the controls/playlist host contract.

Adapters

One adapter per source kind — native <video>, HLS via hls.js, and iframe wrappers for YouTube, Vimeo, Dailymotion and Facebook.

Components

Pluggable Controls and Playlist components receive the engine as their host and re-render from a single state store.

Source families detected automatically from the URL:

Looking for a live example? Open the demo.

Installation

Choose npm for a bundled build, or a CDN for zero build step.

npm / pnpm / yarn

Shell
npm install spark-player

For adaptive HLS in browsers without native support, install the optional peer hls.js (it is loaded lazily):

Shell
npm install hls.js

Zero-build CDN

The demo below proves you need nothing but a browser and a network:

index.html
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/spark-player/dist/spark-player.css">
<div id="player"></div>
<script type="module">
  import { SparkPlayer } from 'https://cdn.jsdelivr.net/npm/spark-player/dist/spark-player.js';

  new SparkPlayer('#player', {
    theme: 'glass',
    playlist: [{ src: 'video.mp4', title: 'My video' }]
  });
</script>
Serving. ES modules must be served over HTTP(S) — opening the file directly with file:// will not work. Any static server (or your host) is enough.

Quick start

A complete player with a mixed-source playlist in a few lines.

app.js
import { SparkPlayer } from 'spark-player';
import 'spark-player/css';

const player = new SparkPlayer('#player', {
  theme: 'glass',
  pageSize: 6,
  autoplayNext: true,
  persist: true,
  playlist: [
    { src: 'media/intro.mp4', title: 'Introduction', poster: 'media/intro.jpg', duration: 92 },
    { src: 'https://example.com/stream.m3u8', title: 'Live stream (HLS)' },
    { src: 'https://www.youtube.com/watch?v=aqz-KE-bpKQ', title: 'YouTube clip' },
    { src: 'https://vimeo.com/76979871', title: 'Vimeo clip' }
  ]
});

player.on('ready', function (e) {
  console.log('ready:', e.item.title, '(' + e.kind + ')');
});

player.on('timeupdate', function (e) {
  // e.currentTime, e.duration
});
The player auto-detects the source kind of every item, so you can mix local MP4s, HLS streams and third-party embeds in a single playlist.

Options

Passed as the second argument to new SparkPlayer(target, options). All are optional.

OptionTypeDefaultDescription
playlistPlaylistItem[][]Items to play. See playlist items.
themeThemeName'glass'Initial theme. One of the six built-ins or a custom name.
pageSize0 | 4 | 6 | 86Items per playlist page; 0 shows all items on one page.
autoplayNextbooleantrueAdvance to the next item when one ends.
mutedbooleanfalseStart muted (useful for autoplay policies).
volumenumber1Initial volume, 0–1.
loopbooleanfalseLoop the playlist (also loops next/prev at the ends).
startIndexnumber0Item to start on.
persistbooleanfalsePersist theme, volume, rate, index and page size to localStorage.
persistKeystring'spark-player'Storage key used when persist is on.
startTimenumber0Resume position (seconds) for the first item. Per-item positions use PlaylistItem.startTime.
resumebooleantrueRemember/restore per-item positions (requires persist).
resumeThresholdnumber5Ignore saved positions shorter than this many seconds.
toastDurationnumber4000Toast auto-dismiss delay in ms; 0 keeps it until dismissed.
controlsbooleantrueRender the built-in controls surface.
playlistPosition'right' | 'bottom' | 'none''right'Where the playlist sits. bottom becomes a mobile bottom sheet.
playlistLayout'grid' | 'list''list'Playlist thumbnail layout.
localestring'en'UI language. Ships en, en-US, en-GB, zh, zh-CN, es, fr, de, ja, ko and pt-BR.
accentstringtheme accentCSS colour overriding --spark-accent.
i18nRecord<string,string>{}Per-string overrides merged over the locale bundle.
hlsLoader(src) => Promise<unknown>dynamic import('hls.js')Supply your own hls.js loader / instance factory.
probeMetadatabooleanfalseProbe missing duration / poster (native + provider oEmbed).
keyboardbooleantrueEnable keyboard shortcuts while the player has focus.
seekStepnumber5Seconds to seek per arrow-key / button press.

Methods

The instance API returned by new SparkPlayer().

MethodKindDescription
new SparkPlayer(target, options?)ctorCreate a player on a selector or element.
ready()asyncPromise that resolves the first time an item becomes ready.
play()actionStart / resume playback.
pause()actionPause playback.
togglePlay()actionPlay if paused, pause if playing.
seek(time)actionSeek to an absolute time in seconds (clamped to duration).
seekBy(delta)actionSeek by a relative number of seconds.
setVolume(v)actionSet volume 0–1.
setMuted(m)actionMute / unmute.
toggleMuted()actionToggle mute state.
setRate(r)actionPlayback rate, clamped 0.25–4.
toggleFullscreen()actionEnter / exit fullscreen.
togglePip()actionEnter / exit picture-in-picture.
toast(message, kind?)feedbackShow an info, success, warn or error notification. Returns a dismiss function.
setTheme(theme)actionSwitch theme (emits themechange).
setTextTrack(lang)actionSelect a caption track by srclang, or null for off.
setQuality(q)actionSelect a quality level (HLS).
getSubtitles()querySubtitle tracks for the current item.
getQualities()queryAvailable quality levels.
getChapters()queryChapters for the current item.
playIndex(i)playlistPlay the item at index i (emits itemclick).
next() / prev()playlistMove to the next / previous item.
setPageSize(n)playlistChange pagination (0 | 4 | 6 | 8).
setPlaylist(items)playlistReplace the whole playlist.
getPlaylist()playlistA copy of the current playlist.
getCurrentItem()playlistThe active playlist item.
addItem(item) / removeItem(i)playlistAdd or remove a single item.
getState()querySnapshot of the current PlayerState.
on(name, fn)eventsSubscribe. Returns an unsubscribe function.
once(name, fn)eventsSubscribe for a single emission.
off(name, fn)eventsRemove a handler.
destroy()lifecycleTear down adapter, components, listeners and DOM.
t(key, vars?)i18nTranslate a UI string using the active locale.

Properties

PropertyTypeDescription
elHTMLElementThe container element the player mounted into.
optionsSparkPlayerOptionsThe live options object.
themesThemeName[]The registered theme names.

Module exports

ExportKindDescription
SparkPlayerclassDefault and named export of the engine.
defineSparkPlayerElement(tag?)fnRegister the <spark-player> custom element (default tag).
autoInit(root?)fnAuto-initialise every [data-spark-player] element.
createI18n(locale?, overrides?)fnBuild a standalone translator.
availableLocalesconstRead-only list of shipped locale identifiers.
detectKind(src, explicit?)fnResolve a SourceKind from a URL.
probeMetadata(item, opts?)fnBest-effort duration / poster probing.
window.SparkPlayerglobalAuto-assigned in browsers for console / UMD use.

Events

27 typed hooks. Subscribe with player.on(name, handler).

Subscribing
const off = player.on('timeupdate', function (e) {
  console.log(e.currentTime, e.duration);
});

player.once('ready', function (e) {
  console.log('first item ready', e.item.title);
});

off(); // unsubscribe later
EventPayloadFired when
mount{ root: HTMLElement }The player has been created and mounted.
ready{ item, kind }An item is ready to play.
play{ index }Playback requested / started.
playingvoidPlayback is actually progressing.
pausevoidPlayback paused.
ended{ index }An item reached its end.
timeupdate{ currentTime, duration }Playhead moved.
seeking{ currentTime }A seek was requested.
seeked{ currentTime }A seek completed.
volumechange{ volume, muted }Volume or mute state changed.
ratechange{ rate }Playback rate changed.
durationchange{ duration }Duration became known / changed.
buffering{ buffering: boolean }Buffering started / stopped.
progress{ buffered }Buffered fraction updated (0–1).
fullscreenchange{ fullscreen }Fullscreen entered / exited.
pipchange{ pip }Picture-in-picture toggled.
errorSparkErrorAn error occurred (see SparkError).
sourcechange{ index, item, kind }The active source changed.
playlistchange{ items, index }The playlist was replaced / mutated.
paginationchange{ page, pageCount, pageSize }Pagination settings changed.
itemclick{ index, item }A playlist item was activated.
themechange{ theme }The theme changed.
captionschange{ lang }The active caption track changed.
qualitychange{ quality }The quality level changed.
resume{ index, item, time }A saved or explicit position was applied.
toastshow{ message, kind }A toast notification was displayed.
destroyvoidThe player was destroyed.

State & types

Snapshots and payload shapes you will handle.

PlayerState

TypeScript
interface PlayerState {
  playing: boolean;
  currentTime: number;
  duration: number;
  buffered: number;      // 0..1
  volume: number;        // 0..1
  muted: boolean;
  rate: number;
  pip: boolean;
  fullscreen: boolean;
  buffering: boolean;
  ended: boolean;
  error: SparkError | null;
  kind: SourceKind | null;
  index: number;
  theme: ThemeName;
  captionLang: string | null;
  quality: string | number;
}

SparkError

TypeScript
interface SparkError {
  code: string;     // e.g. 'mount-error'
  message: string;
  cause?: unknown;
}

Themes

Six built-in themes, switched with setTheme() or the theme option.

glassDark · cyan
neonDark · magenta
desertWarm · amber
glass-lightLight · sky
neon-lightLight · violet
midnightDeep · indigo
Switching at runtime
player.setTheme('neon');

player.on('themechange', function (e) {
  console.log('theme is now', e.theme);
});
Custom themes are just CSS variable sets applied to a .spark--theme-yourname class — see CSS variables.

CSS variables

Every theme is defined by these variables on .spark. Override them globally or per instance.

VariableRole
--spark-accentPrimary accent (progress fill, active states, focus ring).
--spark-accent-fgText / icon colour on top of the accent.
--spark-bgPlayer background.
--spark-surfaceRaised surfaces (menus, panels).
--spark-fgPrimary foreground text / icons.
--spark-mutedSecondary / muted text.
--spark-radiusCorner radius.
--spark-fontFont stack.
--spark-shadowDrop shadow.
--spark-control-hControl-bar height.
--spark-playlist-bgPlaylist panel background.
Custom brand colour
/* globally */
.spark { --spark-accent: #ff5c8a; --spark-radius: 20px; }

/* or per instance via the accent option */
new SparkPlayer('#player', { accent: '#ff5c8a' });

DOM & class names

Stable, BEM-ish class names you can target from your own CSS.

Rendered structure
<div class="spark spark--theme-glass spark--playlist-right" data-theme="glass">
  <div class="spark-stage">
    <div class="spark-video-wrap"><!-- adapter mounts here --></div>
    <div class="spark-overlay"><button class="spark-bigplay"></button></div>
    <div class="spark-controls">…</div>
  </div>
  <div class="spark-playlist">…</div>
</div>
SelectorDescription
.sparkRoot. Modifiers .spark--theme-{name}, .spark--playlist-{right|bottom|none}; states .is-playing, .is-loading, .is-ended, .is-fullscreen, .is-pip.
.spark-stage / .spark-video-wrapVideo area; adapter element mounts inside the wrap.
.spark-controls / .spark-controls__barControls container and bottom bar.
.spark-progressProgress bar; parts __track __buffer __fill __thumb __chapters __tooltip.
.spark-btnControl button; modifiers --play --mute --fullscreen --pip --settings --cc --rate --next --prev.
.spark-time, .spark-volumeTime read-out and volume slider.
.spark-menu / .spark-menu__itemSettings, captions and quality menus.
.spark-playlistPlaylist root; parts __header __list __item __thumb __meta __title __author __duration __pager __pagebtn; item state .is-active.
.spark-sr-only, .is-hiddenUtility classes for accessibility and visibility.

Playlist items

Each item is a PlaylistItem. Only src is required.

TypeScript
interface PlaylistItem {
  id?: string;
  src: string;                 // raw URL or embed URL
  sources?: MediaSource[];     // codec fallbacks: { src, type } -> 
  title?: string;
  author?: string;
  poster?: string;
  duration?: number;           // seconds; auto-probed if omitted
  startTime?: number;          // resume point (seconds) for this item
  thumbnails?: string;         // WebVTT thumbnail-sprite URL
  subtitles?: SubtitleTrack[];
  chapters?: Chapter[];
  kind?: SourceKind;           // override auto-detection
  meta?: Record<string, unknown>;
}
Source kindDetected fromNotes
nativeAnything elseMP4 / WebM / Ogg via <video>; add sources for codec fallback.
hls.m3u8hls.js when needed; native HLS otherwise.
youtubeyoutube.com, youtu.beEmbed wrapper + postMessage where available.
vimeovimeo.comEmbed wrapper.
dailymotiondailymotion.comEmbed wrapper.
facebookfacebook.com/…/videosEmbed wrapper.

Chapters & captions

Rich navigation and accessible captions, per item.

TypeScript
const item = {
  src: 'media/feature.mp4',
  title: 'Feature film',
  subtitles: [
    { src: 'subs/en.vtt', srclang: 'en', label: 'English', default: true, kind: 'captions' },
    { src: 'subs/zh.vtt', srclang: 'zh', label: '中文', kind: 'captions' }
  ],
  chapters: [
    { start: 0, title: 'Intro' },
    { start: 62, title: 'The setup' },
    { start: 240, title: 'The twist' }
  ]
};

Chapters render as markers on the progress bar; captions appear in a language menu (with an Off entry). Select a track programmatically with player.setTextTrack('en').

Internationalisation

Ship eleven locales, or override any string.

Usage
// built-in locale
new SparkPlayer('#player', { locale: 'zh-CN' });

// override specific strings
new SparkPlayer('#player', {
  locale: 'en',
  i18n: { play: 'Start', pause: 'Stop' }
});

// standalone translator
import { createI18n } from 'spark-player';
const t = createI18n('en', { playlist: 'Queue' });
t('playlist'); // 'Queue'

Built-in bundles: en (default), en-US, en-GB, zh, zh-CN, es, fr, de, ja, ko, pt-BR. Regional variants fall back to their base language (pt-PT → pt-BR); unknown locales fall back to en. Use availableLocales to list the shipped bundles. Keys include play, pause, mute, unmute, fullscreen, exitFullscreen, pip, settings, captions, captionsOff, quality, speed, theme, next, prev, playlist, nowPlaying, page, prevPage, nextPage, loading, error, retry.

Integration

Copy-paste recipes for the most common stacks.

Vanilla JS

app.js
import { SparkPlayer } from 'spark-player';
import 'spark-player/css';

const player = new SparkPlayer('#player', {
  playlist: window.__PLAYLIST__,
  theme: 'glass'
});
window.player = player; // handy for debugging

React

Video.jsx
import { SparkPlayerReact } from 'spark-player/react';
import 'spark-player/css';

export function Video({ playlist, theme = 'glass' }) {
  return (
    <SparkPlayerReact
      playlist={playlist}
      theme={theme}
      events={{ ended: () => console.log('finished') }}
    />
  );
}

The spark-player/react entry is StrictMode-safe, cleans up on unmount, and exposes a ref with player, transport, setTheme, setPlaylist, toast and getState. Options are read at mount — pass a new key to reconfigure. React is an optional peer.

Vue 3

Video.vue
<template>
  <div ref="host"></div>
</template>

<script setup>
import { onMounted, onBeforeUnmount, ref } from 'vue';
import { SparkPlayer } from 'spark-player';
import 'spark-player/css';

const props = defineProps({ playlist: Array });
const host = ref(null);
let player;

onMounted(() => { player = new SparkPlayer(host.value, { playlist: props.playlist }); });
onBeforeUnmount(() => { if (player) player.destroy(); });
</script>

WordPress

shortcode
[spark_player src="https://example.com/video.mp4" title="My video" theme="glass"]

[spark_player theme="neon" locale="fr" page_size="6" start_time="42"]
  https://example.com/video-b.mp4
[/spark_player]

Ships a plugin in wordpress/ with a [spark_player] shortcode and a server-rendered Spark Player block. It enqueues one CSS file plus dist/spark-player.umd.js, needs no jQuery, escapes every attribute and rejects non-HTTP sources. See docs/WORDPRESS.md for the full attribute table and asset resolution.

Web component

HTML
<spark-player>
  <script type="application/json">
    { "theme": "neon", "playlist": [{ "src": "video.mp4", "title": "Hi" }] }
  </script>
</spark-player>

<script type="module">
  import { defineSparkPlayerElement } from 'spark-player';
  defineSparkPlayerElement();
</script>

Keyboard & accessibility

Built for keyboard-first and assistive technology users.

KeyAction
Space / KPlay / pause
→ / ←Seek forward / back by seekStep
↑ / ↓Volume up / down
MMute / unmute
FToggle fullscreen
N / PNext / previous item
TabMove focus through every control
Enter / SpaceActivate the focused control or playlist item
  • Every interactive control carries an aria-label translated via the active locale, and type="button".
  • Root state (is-playing, is-fullscreen, is-pip) reflects playback for external styling and testing.
  • The player honours prefers-reduced-motion and uses semantic landmarks.
  • Set keyboard: false to opt out of global shortcuts.

Browser support

Modern evergreen browsers, desktop and mobile.

Chrome / Edge

Full support. HLS via hls.js; native PiP.

Firefox

Full support. HLS via hls.js; native PiP.

Safari / iOS

Full support, with native HLS where available.

Mobile

Responsive layout with bottom-sheet playlist.

Third-party embeds (YouTube, Vimeo, Dailymotion, Facebook) require the page to be served over HTTPS to function reliably.

FAQ

Short answers to the usual questions.

Do I need hls.js?
Only for HLS streams in browsers without native HLS support. Install it as an optional peer; the player loads it lazily. Safari plays HLS natively without it.
Does it work without a bundler?
Yes. Load the ESM bundle and stylesheet from a CDN and initialise with a module script — see Installation.
Can I mix source types in one playlist?
Absolutely. Each item's kind is auto-detected from its URL (or forced with kind), so MP4s, HLS streams and embeds can share a single playlist.
How do I theme it?
Pick one of six built-in themes, or override the CSS variables on .spark (or per instance with the accent option). See CSS variables.
Does it support server-side rendering?
The player is browser-only and needs the DOM. In SSR frameworks, create it inside useEffect / onMounted after hydration.
What license is it under?
MIT. Free for commercial and personal projects.