Control audio and video elements from JavaScript

The <video> element has methods, properties/attributes and events that can be manipulated with JavaScript. Using the DOM API it’s possible to manipulate an audio or video element as a JavaScript object that has:

    • Methods for controlling the behavior, such as play(), pause(), etc.;
    • Properties (duration, current position, etc.), either in read/write mode (such as volume), or in read-only mode (such as encoding, duration, etc.);
    • Events generated during the life cycle of the element that can be processed using JavaScript callbacks. It is also possible to send events to control the video player.

Like any HTML element, the <video> element can be manipulated/created using the DOM JavaScript API. Here is an example of programmatically creating a <video> element:

  1. var video = document.createElement(‘video’);
  2. video.src = ‘video.mp4’;
  3. video.controls = true;
  4. document.body.appendChild(video);

This will create a complete video player for the file “video.mp4”, with control buttons, and will add it to the <body> element of the page.

example:

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s