/ #javascript #node #testing 

Managing Your Videos With HTML and JavaScript

This article explains how to manage video content with HTML and JavaScript. Video content has become a significant part of Internet use, and it plays a large role in user experience. The ability to effectively include video content in your sites can help you improve user experience.

In this article, you’ll learn some basic HTML and JavaScript tools for working with video. You’ll also learn how to make some common customizations to your videos to give your users the best experience possible.

Table of Contents

Basic Tools for Working With Videos

When working with video, you can use vanilla HTML and CSS for most aspects or you can use a combination of HTML, CSS, and JavaScript. Below are some of the basic tools you need.

HTML

The easiest way to include video on your pages is with the <video> element, which enables you to embed video.

The most useful <video> attributes include:

  • controls - a basic control bar that includes buttons for playback, volume, and a progress bar. With this attribute, you can also control settings for media download, fullscreen, and picture-in-picture.
  • autoplay - begins playback while the rest of your page loads. This attribute doesn’t work with iOS mobile devices. Some browsers, such as Chrome 70.0, require the muted attribute to be present for autoplay to work.
  • loop - loops back to the beginning and resumes playback after your video ends.
  • muted - media plays without sound by default. This attribute has a default value of "false" so you need to set it to "true" to apply this feature.
  • poster - an image is displayed before playback starts. This attribute is designed for splash screens or advertising. It is not shown if autoplay is included.
  • preload - used for buffering media. Values include none for no buffering, auto for buffering on site load, and metadata for buffering of metadata only.
  • height and width - enables you to define video height and width without using CSS. The caveat of these attributes is that you can only define values in pixels. You cannot use percentages or auto as you can with CSS.

An alternative to <video> is the <iframe> element, which is used to embed video from external sources, such as YouTube or Vimeo. You use <iframe> to embed external HTML pages into your page. It does not allow you to customize video to the extent that <video> does.

JavaScript (JS)

You can control the same aspects using JS scripting as with the <video> element. For example, source control, loading, or playback. Javascript enables you to return a variety of information from video methods, events, and properties through the Document Object Model (DOM). DOM is the interface between your HTML and JS functions.

To write JS scripts for videos, you should be familiar with the HTMLMediaElement API. This API enables you to programmatically control and monitor your video players. HTMLMediaElement is supported by all browsers.

When creating scripts for managing your video content, you may find the following open-source audio/video tools useful:

  • jPlayer - works as a jQuery plugin with a comprehensive API. It includes multi-codec and cross-platform support. jPlayer is also available for React.

  • Mediaelement.js - a media framework that supports media files, streaming content, and embedded players. You can also use it as a standalone library or via plug-ins.

How to Manage Your Videos

There are many ways you can customize your video content to improve user experience and site performance. Below are three basic aspects you can start with to manage your videos.

Responsive Sizing

Responsive videos, like responsive images, are media that adjust to the size and format of a recipient’s device. Responsive video content might entail video with different cropping, different quality levels, or automatic adjustment when a screen is rotated.

When making videos responsive, keep in mind that video maintains its aspect ratio regardless of how you define height and width. Aspect ratio determines the shape of the video, such as 4:3 (standard), 16:9 (HD), or 1:1 (Instagram). If your sizes do not preserve this ratio, any additional space will be filled with a solid background color by default.

Outside the <video> tag, you can use CSS to set the width to 100% and height to auto. This will expand your video to the maximum available size. Using this method is an easy way to enable responsive design for full-size videos without needing to know your user’s device specs.

Alternatively, you can use max-width if you want your video displayed at a specific size but to scale down when necessary. max-width specifies the largest size you want your video displayed at.

When using <iframe>, you can use a wrapper with a set aspect ratio or can use JS and jQuery to adjust the hard-coded height and width attributes. jQuery is a library built into JS, designed to make interaction with the DOM easier.

Here’s an example that shows how you can adjust <iframe> size:

$(window).on('resize', function() {
   $('iframe').each(function() {       
      var $this = $(this);   
      if ($this.data('video-aspect-ratio')) {        
         var dimensions = $this.data('video-aspect-ratio');
         dimensions = dimensions.split(':');      
         var newHeight = ($this.width()/ dimensions[0]) *     dimensions[1];
            newHeight = parseInt(newHeight);        
            $this.css('height', newHeight + 'px');      
      }           
   });
}).trigger('resize');

Text Tracks

Text tracks are useful for increasing the accessibility of your videos. These tracks are added on top of video files using WebVTT files and the <track> element. WebVTT files define the text to be displayed and include metadata for timing, styling, and positioning. The <track> element defines .vtt file sources and informs the browser of the track type.

The most commonly included tracks include:

  • Subtitles - text translations of dialog into another language.
  • Captions - transcriptions of dialog or sounds that provide accessibility for hearing-impaired viewers.
  • Timed descriptions - text that is spoken aloud and provides accessibility for visually impaired viewers.

Below is an example of how to include text tracks with your video. In this example, the kind attribute defines the track type and srclang defines the language.

<video controls> 
<source src="example.mp4" type="video/mp4"> 
<source src="example.webm" type="video/webm"> 
<track kind="subtitles" src="subtitles_en.vtt" srclang="en"> 
</video>

You can include multiple tracks and track types but the ability to switch tracks is not included in browsers by default. To allow switching, you need to add this functionality with JavaScript. Accomplishing track switching requires a larger amount of scripting than can be included here, but you can find a tutorial here.

Format

The format of your videos determines whether or not your content is playable on a user’s device. To ensure that your videos can be viewed, you should include a preferred format and at least one fallback format.

When defining your video <source> elements, the first element you name is the default. Any <source> elements that follow are fallback formats. Your user’s browser will work through sources from top to bottom until it encounters one that is supported.

You can also define the sources to use with JavaScript. This enables you to list formats in any order you wish and still serve content according to browser specs.

Here’s an example that shows how to serve formats according to specs:

var myVideo = document.createElement('video'); 

if (myVideo.canPlayType('video/mp4')) { 
  myVideo.setAttribute('src','videofile.mp4'); 
} 
else if (myVideo.canPlayType('video/webm')) { 
  myVideo.setAttribute('src','videofile.webm'); 
}

Conclusion

Hopefully, this article helped you understand the basics of managing your videos with HTML and JavaScript. When you add video content, make sure to address the aspects covered here. Taking the time to optimize these aspects can help you ensure a positive experience for your users.

Once you’ve got these features perfected, you might want to consider adding streaming capabilities to your sites. Streaming can help you deliver much larger and higher quality video files without loss of performance.

Author

Gilad David Maayan

Gilad David Maayan is a technology writer who has worked with over 150 technology companies including SAP, Samsung NEXT, NetApp and Imperva, producing technical and thought leadership content that elucidates technical solutions for developers and IT leadership.

Get The Jest Handbook (100 pages)

Take your JavaScript testing to the next level by learning the ins and outs of Jest, the top JavaScript testing library.