MediaElement.js: Advanced HTML5 Video and Audio Player Plugin

File Size: 534 KB
Views Total: 26249
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   
MediaElement.js: Advanced HTML5 Video and Audio Player Plugin

MediaElement.js is a JavaScript HTML5 video and audio player that wraps native <video> and <audio> elements in a consistent custom player UI.

It handles MP4, MP3, WebM, HLS, MPEG-DASH, YouTube, Vimeo, Twitch, DailyMotion, Facebook, and SoundCloud through native playback and optional renderers.

jQuery is optional for direct JavaScript initialization, but the $.fn.mediaelementplayer syntax requires jQuery to load before MediaElement.js.

Features

  • Creates a consistent player UI for HTML5 video and audio elements.
  • Works through plain JavaScript or the classic jQuery plugin call.
  • Uses renderer files for embedded media providers and streaming formats.
  • Supports captions, chapters, fullscreen controls, keyboard controls, volume controls, and custom control ordering.
  • Exposes media properties, methods, and events that map closely to the HTMLMediaElement API.

Table Of Contents:

How to Use It

1. Install MediaElement.js from npm, Git, a package download, or a CDN. For a classic browser setup, include the stylesheet, jQuery if you want the jQuery plugin syntax, the main player script, and any renderer files required by your media sources.

<!-- Core player styles -->
<link rel="stylesheet" href="/path/to/build/mediaelementplayer.min.css" />

<!-- jQuery is required only for $.fn.mediaelementplayer() -->
<script src="/path/to/jquery.min.js"></script>

<!-- Core player script -->
<script src="/path/to/build/mediaelement-and-player.min.js"></script>

<!-- Optional renderers. Load only the renderers you need. -->
<script src="/path/to/build/renderers/dailymotion.min.js"></script>
<script src="/path/to/build/renderers/facebook.min.js"></script>
<script src="/path/to/build/renderers/soundcloud.min.js"></script>
<script src="/path/to/build/renderers/twitch.min.js"></script>
<script src="/path/to/build/renderers/vimeo.min.js"></script>
<script src="/path/to/build/renderers/youtube.min.js"></script>

2. Add a normal HTML5 video or audio element. Use <source> elements when you need multiple formats or streaming sources.

<video id="product-video" width="640" height="360" controls preload="none" poster="/media/poster.jpg">
  <source src="/media/product-demo.mp4" type="video/mp4" />
  <source src="/media/product-demo.webm" type="video/webm" />
  <track src="/media/product-demo-en.vtt" kind="subtitles" srclang="en" label="English" default />
</video>

3. Initialize the player with plain JavaScript when you do not need jQuery.

var productVideo = new MediaElementPlayer('product-video', {
  features: ['playpause', 'current', 'progress', 'duration', 'tracks', 'volume', 'fullscreen'],
  stretching: 'responsive',
  success: function(media, node, instance) {
    media.addEventListener('ended', function() {
      console.log('Video finished');
    });
  }
});

4. Use the jQuery plugin syntax in legacy jQuery projects.

$('#product-video').mediaelementplayer({
  features: ['playpause', 'current', 'progress', 'duration', 'tracks', 'volume', 'fullscreen'],
  stretching: 'responsive',
  success: function(media, node, instance) {
    console.log('MediaElementPlayer is ready');
  },
  error: function(error, media, node) {
    console.log('Media could not load');
  }
});

5. Use the automatic start option when you prefer configuration in markup. Add mejs__player to the media element and pass options through data-mejsoptions.

<audio
  id="podcast-player"
  class="mejs__player"
  src="/audio/episode-01.mp3"
  controls
  preload="none"
  data-mejsoptions='{"audioWidth": 640, "features": ["playpause", "current", "progress", "duration", "volume"]}'>
</audio>

Options

MediaElement.js accepts native <video> and <audio> attributes, plus standalone MediaElement settings and MediaElementPlayer UI settings.

Native Media Attributes

  • autoplay: Starts playback when the browser permits autoplay.
  • controls: Shows native media controls before MediaElement.js replaces the UI.
  • height: Sets the media element height in pixels.
  • width: Sets the media element width in pixels or percentages.
  • loop: Repeats the media after playback ends.
  • muted: Mutes audio output. This often matters for autoplay.
  • poster: Sets the poster image shown before playback.
  • preload: Controls browser preload behavior. Common values are auto, metadata, and none.
  • src: Sets the media file URL when you do not use nested <source> elements.
  • tabindex: Controls keyboard tab order for the media element.
  • title: Adds a descriptive title for the media element.

Standalone MediaElement Options

  • renderers (Default: []): Lists the renderer IDs to use for the current media source.
  • fakeNodeName (Default: 'div'): Sets the container element name used by MediaElement.
  • iconSprite (Default: 'mejs-controls.svg'): Sets the path to the SVG icon sprite.
  • success (Default: null): Runs after the media source loads. MediaElementPlayer passes media, node, and instance.
  • error (Default: null): Runs when the media source fails to load.
  • dailymotion (Default: {}): Sets Dailymotion renderer options.
  • dash (Default: {}): Sets MPEG-DASH renderer options such as debug, DRM, and dash.js path settings.
  • facebook (Default: {}): Sets Facebook video renderer options.
  • hls (Default: {}): Sets HLS renderer options and the HLS library path when needed.
  • youtube (Default: {}): Sets YouTube renderer options such as nocookie and imageQuality.

MediaElementPlayer Options

  • classPrefix (Default: 'mejs__'): Sets the class prefix for generated player elements.
  • poster (Default: ''): Overrides the poster attribute with a configured poster URL.
  • showPosterWhenEnded (Default: false): Shows the poster again after video playback ends.
  • showPosterWhenPaused (Default: false): Shows the poster while video playback pauses.
  • defaultVideoWidth (Default: 480): Sets the fallback video width when the element has no width.
  • defaultVideoHeight (Default: 270): Sets the fallback video height when the element has no height.
  • videoWidth (Default: -1): Overrides the video element width when set.
  • videoHeight (Default: -1): Overrides the video element height when set.
  • defaultAudioWidth (Default: 400): Sets the fallback audio player width.
  • defaultAudioHeight (Default: 30): Sets the fallback audio player height.
  • audioWidth (Default: -1): Sets the audio player width.
  • audioHeight (Default: -1): Sets the audio player height.
  • defaultSeekBackwardInterval (Default: function): Sets the default backward seek interval.
  • defaultSeekForwardInterval (Default: function): Sets the default forward seek interval.
  • setDimensions (Default: true): Sets player dimensions through JavaScript.
  • startVolume (Default: 0.8): Sets the initial volume from 0 to 1.
  • loop (Default: false): Repeats the media after playback ends.
  • autoRewind (Default: true): Moves playback back to the start when the media ends.
  • enableAutosize (Default: true): Resizes the player from media dimensions.
  • timeFormat (Default: 'mm:ss'): Sets the displayed time format.
  • alwaysShowHours (Default: false): Forces hour display in the time code.
  • showTimecodeFrameCount (Default: false): Shows frame count in the time code.
  • framesPerSecond (Default: 25): Sets the frame count base when frame count display is active.
  • autosizeProgress (Default: true): Calculates progress bar width from the surrounding controls.
  • alwaysShowControls (Default: false): Keeps controls visible during video playback.
  • hideVideoControlsOnLoad (Default: false): Hides video controls while media loads.
  • hideVideoControlsOnPause (Default: false): Hides video controls while media pauses.
  • clickToPlayPause (Default: true): Lets the video area toggle play and pause on click.
  • controlsTimeoutDefault (Default: 1500): Sets the default control hiding delay in milliseconds.
  • controlsTimeoutMouseEnter (Default: 2500): Sets the mouse enter timer delay.
  • controlsTimeoutMouseLeave (Default: 1000): Sets the mouse leave timer delay.
  • iPadUseNativeControls (Default: false): Uses native controls on iPad.
  • iPhoneUseNativeControls (Default: false): Uses native controls on iPhone.
  • AndroidUseNativeControls (Default: false): Uses native controls on Android.
  • features (Default: [...]): Controls the visible player features and their order.
  • useDefaultControls (Default: false): Uses all default controls and appends extra plugin controls.
  • isVideo (Default: true): Marks the instance as video during dynamic setup.
  • stretching (Default: 'auto'): Controls the video scaling mode. Values include auto, responsive, fill, and related modes supported by the player.
  • enableKeyboard (Default: true): Turns keyboard controls on for the player.
  • pauseOtherPlayers (Default: true): Pauses other player instances when the current player starts.
  • ignorePauseOtherPlayersOption (Default: true): Ignores the global pause-other-players behavior for the current player.
  • secondsDecimalLength (Default: 0): Sets decimal places for seconds when frame display is active.
  • customError (Default: null): Sets custom HTML or a callback for load errors.
  • keyActions (Default: [...]): Defines keyboard shortcuts and their callbacks.
  • duration (Default: -1): Sets an initial duration value for time calculations.
  • timeAndDurationSeparator (Default: '<span> &#124; </span>'): Sets the separator between current time and total duration.
  • hideVolumeOnTouchDevices (Default: true): Hides volume controls on touch devices.
  • enableProgressTooltip (Default: true): Shows a time tooltip on the progress bar.
  • useSmoothHover (Default: true): Uses a smooth hover effect on the progress bar.
  • forceLive (Default: false): Shows the live broadcast state and hides the progress bar.
  • audioVolume (Default: 'horizontal'): Sets audio volume slider orientation.
  • videoVolume (Default: 'vertical'): Sets video volume slider orientation.
  • usePluginFullScreen (Default: true): Uses plugin fullscreen handling.
  • useFakeFullscreen (Default: false): Uses fake fullscreen mode for mobile fallback cases.
  • hideCaptionsButtonWhenEmpty (Default: true): Removes the captions button when no subtitle tracks exist.
  • toggleCaptionsButtonWhenOnlyOne (Default: false): Turns the captions control into a toggle when only one track exists.
  • defaultTrackLine (Default: -3): Sets the default cue line for VTT cues that use auto.
  • autoplayCaptionLanguage (Default: null): Turns on captions for the matching language automatically.
  • chaptersLanguage (Default: null): Sets the language used for chapter tracks.
  • hideScreenReaderTitle (Default: false): Hides the generated screen reader title when your site adds its own title.
  • tracksText (Default: null): Sets accessible text for the captions button.
  • chaptersText (Default: null): Sets accessible text for the chapters button.
  • muteText (Default: null): Sets accessible text for the mute button.
  • unmuteText (Default: null): Sets accessible text for the unmute button.
  • allyVolumeControlText (Default: null): Sets accessible text for the volume control.
  • fullscreenText (Default: null): Sets accessible text for the fullscreen button.
  • playText (Default: null): Sets accessible text for the play button.
  • pauseText (Default: null): Sets accessible text for the pause button.

Advanced Usages

Set Audio Player Width

Use audioWidth when you need a fixed audio player width. Use defaultAudioWidth when you only need a fallback width for audio elements that do not define their own width.

$('#podcast-player').mediaelementplayer({
  audioWidth: 640,
  audioHeight: 40,
  features: ['playpause', 'current', 'progress', 'duration', 'volume']
});

Control Captions and Tracks

Add a <track> element to the media markup and keep 'tracks' in the features array. Use autoplayCaptionLanguage when a specific caption language should start active.

<video id="training-video" width="640" height="360" controls preload="none">
  <source src="/media/training.mp4" type="video/mp4" />
  <track src="/media/training-en.vtt" kind="subtitles" srclang="en" label="English" default />
</video>
$('#training-video').mediaelementplayer({
  features: ['playpause', 'current', 'progress', 'duration', 'tracks', 'volume', 'fullscreen'],
  autoplayCaptionLanguage: 'en',
  hideCaptionsButtonWhenEmpty: true,
  toggleCaptionsButtonWhenOnlyOne: true
});

Change Control Order

The features array controls which buttons appear and their order in the control bar.

$('#lesson-video').mediaelementplayer({
  features: ['playpause', 'progress', 'current', 'duration', 'tracks', 'fullscreen']
});

Resize a Player Instance

Call setPlayerSize(width, height) when the player needs a new size after initialization.

var lessonPlayer = new MediaElementPlayer('lesson-video');

lessonPlayer.setPlayerSize(960, 540);

Use Specific Renderers

Load renderer files after the main player file. Then pass the renderer IDs through the renderers option when you need a controlled renderer order.

mejs.Renderers.order = ['native_hls', 'html5'];

$('video').mediaelementplayer({
  renderers: ['native_hls', 'html5'],
  hls: {
    debug: false
  }
});

Properties

  • autoplay: Gets or sets autoplay state.
  • buffered: Returns buffered time ranges.
  • controls: Gets or sets controls state.
  • currentSrc: Returns the current media URL.
  • currentTime: Gets or sets the playback position in seconds.
  • duration: Returns media length in seconds after metadata loads.
  • ended: Returns playback completion state.
  • error: Returns the current media error object.
  • loop: Gets or sets loop state.
  • muted: Gets or sets muted state.
  • paused: Returns pause state.
  • readyState: Returns the current ready state.
  • seeking: Returns the seeking state.
  • src: Gets or sets the media source.
  • volume: Gets or sets the volume level.
  • seekUserInteraction: Returns whether the last seek came from user interaction.

API Methods

// Reload the current media element.
myPlayer.load();

// Start playback.
myPlayer.play();

// Pause playback.
myPlayer.pause();

// Destroy the player instance.
myPlayer.remove();

// Check support for a MIME type in the current renderer.
myPlayer.canPlayType('video/mp4');

// Set player width and height.
myPlayer.setPlayerSize(640, 360);

// Set or clear the poster image.
myPlayer.setPoster('/media/poster.jpg');

// Mute or unmute the player.
myPlayer.setMuted(true);

// Set the current playback time in seconds.
myPlayer.setCurrentTime(30);

// Get the current playback time.
myPlayer.getCurrentTime();

// Set volume from 0 to 1.
myPlayer.setVolume(0.75);

// Get the current volume.
myPlayer.getVolume();

// Change the media source.
myPlayer.setSrc('/media/new-video.mp4');

// Get the current media source.
myPlayer.getSrc();

Events

MediaElement.js exposes standard media events and a captions change event. Attach listeners in the success callback so the media wrapper is ready.

var analyticsPlayer = new MediaElementPlayer('analytics-video', {
  success: function(media, node, instance) {
    media.addEventListener('loadedmetadata', function() {
      console.log('Metadata loaded');
    });

    media.addEventListener('playing', function() {
      console.log('Playback started');
    });

    media.addEventListener('pause', function() {
      console.log('Playback paused');
    });

    media.addEventListener('ended', function() {
      console.log('Playback ended');
    });

    media.addEventListener('captionschange', function() {
      console.log('Caption state changed');
    });
  }
});

Alternatives and Related Resources

FAQs

Does MediaElement.js require jQuery?

No. You can initialize MediaElement.js with new MediaElementPlayer() in plain JavaScript. The jQuery plugin call $(selector).mediaelementplayer() requires jQuery.

How do I change the MediaElementPlayer audio width?

Set audioWidth in the player options. Use defaultAudioWidth only when you want a fallback width for audio elements that do not define their own size.

How do I show captions in MediaElement.js?

Add a <track> element to the media markup and keep 'tracks' in the features array. Use autoplayCaptionLanguage when one caption language should start active.

Why does autoplay fail in some browsers?

Current browser autoplay policies usually block unmuted autoplay. Add the muted attribute when autoplay is required and test the behavior in your target browsers.

How do I listen for playback events?

Attach listeners such as playing, pause, ended, and timeupdate to the media wrapper inside the success callback.

Changelog

v7.1.0 (2025-11-12)

  • Fixed fullscreen scaling and rotation bugs across browsers and devices.
  • Added demo coverage for the fake fullscreen option.

v7.0.7 (2024-12-17)

  • Removed an accidental symlink from the repository.

v7.0.6 (2024-12-17)

  • Added keyboard controls for play and pause on the container element.
  • Added screen reader text for current time and total duration.

v7.0.5 (2024-04-26)

  • Fixed focus behavior when default subtitles load.

v7.0.4 (2024-04-25)

  • Fixed focus behavior when default subtitles load.
  • Improved performance by removing an extra test logic event.

v7.0.3 (2024-01-29)

  • Fixed initial caption loading for HLS and MPEG-DASH renderers.

v7.0.2 (2023-11-14)

  • Fixed iframe player errors.
  • Fixed iframe scaling inside player containers.

v7.0.1 (2023-10-31)

  • Fixed hidden caption toggle state.

v7.0.0 (2023-03-28)

  • Removed Flash support.
  • Improved HLS and MPEG-DASH caption handling.
  • Fixed Firefox mouseout behavior.

v6.0.0 (2023-01-30)

  • Added browser-native subtitle support.
  • Removed custom VTT and DFXP parsing.
  • Renamed startLanguage to autoplayCaptionLanguage.
  • Added chaptersLanguage and defaultTrackLine.

This awesome jQuery plugin is developed by johndyer. For more Advanced Usages, please check the demo page or visit the official website.