Play Video in JavaScript: A Practical Guide for Developers

Learn how to play, pause, seek, and control HTML5 video with JavaScript. This guide covers the video API, autoplay nuances, custom controls, keyboard interactions, accessibility, and common pitfalls for robust playback.

JavaScripting
JavaScripting Team
·5 min read
Quick AnswerDefinition

Video playback in the browser is handled by the HTMLVideoElement. In JavaScript you can play, pause, seek, adjust currentTime, and set playbackRate, all while respecting autoplay policies and accessibility. This guide demonstrates practical code to control video from JS, with error handling and UX-friendly UI, plus event listeners, custom controls, and keyboard interactions for a robust player.

Embedding and Accessing the Video Element

Modern web apps rely on the HTML5 video element to render and control media directly in the browser. Start by declaring a semantic, accessible video tag with sources and fallbacks. Then grab a reference in JavaScript to perform programmatic actions like play(), pause(), and seeking. The examples below show a minimal setup and a few initial event listeners to log playback state.

HTML
<video id="player" width="640" height="360" preload="metadata" controls aria-label="Sample video" poster="poster.jpg"> <source src="videos/sample.mp4" type="video/mp4"> Your browser does not support HTML5 video. </video>
JavaScript
const player = document.getElementById('player'); player.addEventListener('loadedmetadata', () => { console.log('Duration:', player.duration); }); player.addEventListener('play', () => console.log('Playing')); player.addEventListener('pause', () => console.log('Paused'));
  • This setup ensures you can inspect properties like duration and track basic events.
  • You can extend with additional sources or dynamic source switching as needed.
HTML
<!-- Alternative: multiple sources for compatibility --> <video id="playerAlt" width="640" height="360" preload="metadata" controls> <source src="videos/sample.webm" type="video/webm"> <source src="videos/sample.mp4" type="video/mp4"> </video>

Why it matters: A well-structured video element is the foundation for reliable playback across devices and browsers, enabling clean integration with your JavaScript logic.

sectionCodeExamples

sectionDetails

Steps

Estimated time: 60-90 minutes

  1. 1

    Create the video element

    Add a semantic video element with sources and controls. Ensure a readable aria-label and a poster image for initial UX. This step establishes the DOM hook you’ll use from JavaScript.

    Tip: Keep sources accessible; provide a fallback message for older browsers.
  2. 2

    Hook the element in JavaScript

    Grab a reference to the video element and attach basic event listeners for logging or UX feedback. This is your starting point for programmatic control.

    Tip: Use const for the element reference to prevent reassignment.
  3. 3

    Play and pause programmatically

    Call play() and pause() on the element, handling the returned Promise to catch autoplay rejections or user gesture requirements.

    Tip: Always handle the promise to avoid uncaught errors.
  4. 4

    Implement seeking and speed control

    Modify currentTime to seek and playbackRate to adjust speed. Validate currentTime against duration to avoid errors.

    Tip: Clamp values to valid ranges to prevent exceptions.
  5. 5

    Add a basic custom UI

    Create a simple control panel (buttons for play/pause, seek, volume) and wire it to the video API. Improve accessibility with ARIA attributes.

    Tip: Ensure keyboard focus management for accessibility.
  6. 6

    Test across browsers and devices

    Test with different video codecs, networks, and device classes. Validate caption tracks and fallback content.

    Tip: Use a variety of test files to catch cross-browser issues early.
Pro Tip: Prefer muted autoplay for a smoother UX in modern browsers.
Warning: Autoplay may be blocked without a user gesture or muted state.
Note: Provide captions to improve accessibility and inclusivity.

Prerequisites

Required

  • Basic understanding of HTML and JavaScript
    Required
  • A modern web browser with HTML5 video support
    Required

Optional

  • A code editor and a local server for testing (optional but recommended)
    Optional
  • Accessible captions or subtitles (recommended for accessibility)
    Optional

Keyboard Shortcuts

ActionShortcut
Toggle play/pauseWhen focus is on the video or playback container
Seek backward 5sWhile the video has focus or your custom player is activeLeft Arrow
Seek forward 5sWhile the video has focus or your custom player is activeRight Arrow
Mute/UnmuteToggle volume on the active video elementM
FullscreenEnter or exit fullscreen on the video elementF

Questions & Answers

What is the HTMLVideoElement, and how do I access it in JavaScript?

The HTMLVideoElement represents a video in the DOM. Access it with document.getElementById or querySelector and manipulate it via its API (play, pause, currentTime, volume, etc.). Event listeners help monitor state like play, pause, and ended.

You grab the video element from the page and use its API to control playback.

Why does video.play() sometimes fail even after a user gesture?

Play() returns a Promise. It can reject due to autoplay policies, missing user gesture, or media source issues. Always handle rejection to provide fallback UX or informative messages.

Play() can fail if the browser blocks autoplay even after a click, so handle errors gracefully.

How can I ensure autoplay works across browsers?

Autoplay typically requires the video to be muted or a user gesture. Consider starting with muted autoplay or pausing until user interaction occurs, and avoid relying on autoplay for critical UX.

Most browsers only autoplay muted videos or after a user action, so plan for that.

How do I implement captions for accessibility?

Add a <track> element with kind='captions' and a proper srclang. Provide a fallback text and ensure screen readers announce captions when enabled.

Captions help users understand audio content and improve accessibility.

What are common cross-origin considerations for video?

If pulling video from another origin, ensure CORS headers allow access and be aware of cross-origin restrictions that can affect playback or metadata access.

Cross-origin rules can block media data, so check server headers and policies.

What to Remember

  • Use HTMLVideoElement as the foundation for playback control
  • Always handle video.play() as a Promise
  • Respect autoplay restrictions with user gestures or mute
  • Add accessible controls and captions for inclusive UX

Related Articles