HTML5 Video Tag - Video attributes tutorial

HTML5 video tag adds and manages video content on a webpage with its various attributes. It is one of the smart way to diversify website content. Search engines are fond of video content as it is gets most user engagement. It helps in gaining better rankings in Search results.

The video tag was introduced in HTML5 as the demand of video content increased. The HTML5 <video> tag displays a video player in the webpage with customized controls. These controls can be controlled by attributes of video tag. You will get a complete attribute tutorial, let's first see the basic example of how to add video in a webpage:

HTML5 Video tag Example

The type attribute defines the format of the video file used.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> HTML Video </title>
</head>
<body>
<video width="480" height="320" controls>
<source src="html-video.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
</body>
</html>

Output

HTML Video Tag Examples

Breakdown of HTML5 Video tag attributes

The HTML5 video tag has many attributes and nested tags also. Let's breakdown the its structure:

  • Video Tag: It is a paired tag and all the code regarding video will be written inside this. It displays a video player in the webpage.
  • 'height' and 'width' attribute: These attributes specify the size of the player.
  • 'controls' attribute: It adds video controls in the player like play, pause and volume.
  • <source> tag: It specifies the characteristics of the video to be added like its location(URL) and type. You can add multiple source tag inside the same video tag to add the video file with different video type. The browser will play the first supported video type.
  • 'src' attribute: This attribute is an alternative for <source> tag. If you want to add a single type video file then use this attribute inside video tag. It is also used inside source tag to add location of video file.
  • 'type' attribute: It specifies the type of the video file.

History of HTML5 Video tag

In HTML4 and earlier versions of HTML, video files could only be added to websites using various multimedia plugins (e.g., Adobe Flash). The <video> tag was introduced in HTML 5 (officially referred to as HTML5 - without the space).It is now widely implemented in the major browsers.

HTML5 has a native video element that supports three video formats (MP4, WebM and Ogg), making it easier to embed videos in a webpage.


Video Controls

It is always recommended to add HTML5 video controls to your player. Using special buttons in the player window, the user can manually start and stop the video, skip to specific place using the slider, or toggle between window and full screen video display, control volume. To add video controls, include the controls attribute.

Fallback content

If the video cannot be played in any format provided, the user will see the text known as the fallback content. It is the only content within the <video> tags. Use it to provide information to the user or a direct link to the video file.

Specifying Sources

HTML 5 Support attributes like preload, autoplay, loop and more. It is also mandatory to define the source for the video. You can do it by using a simple src attribute, but it is recommended to choose the <source> tags for that:

The reason this is considered a better practice is because use of <source> tags allows you to define multiple sources. The HTML5 video player supports three formats (.mp4, .ogg and .webM), but not all of them have the same level of browser support. This means you can add video in different formats to ensure video playback.

The source tag lets you specify multiple formats as a fallback in case the user's browser doesn't support one of them. For example:

Syntax
<video controls>
<source src="devstories.webm" type='video/webm;codecs="vp8, vorbis"'/>
<source src="devstories.mp4" type='video/mp4;codecs="avc1.42E01E, mp4a.40.2"'/>
</video>

When the browser parses the <source> tag, it uses the optional type attribute to help decide which file to download and play. If the browser supports WebM and has the VP8 and Vorbis codecs, it will play devstories.webm, if not, it will check if it can play MPEG-4 videos with the avc1.42E01E and mp4a.40.2 codecs, and so forth.

Note: To improve performance, you should always include the type attribute in the source element. Otherwise the browser will need to load each video file until it can find one that it can play!

Media Fragments

Adding a media fragment to the media URL, you can specify the exact portion you want to play. To add a media fragment, you simply add #t=[start_time][,end_time] to the media URL. For example, to play the video between seconds 10 through 20, you could specify:

Syntax
<source src="devstories.webm#t=10,20" type='video/webm;codecs="vp8, vorbis"' />


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> HTML Media Fragment </title>
</head>
<body>
<video width="480" height="320" controls>
<source src="html-video.mp4#t=00:00:05" type="video/mp4">
</body>
</html>

You can also specify the times in hours:minutes:seconds, such as #t=00:01:05 to start the video at one minute, five seconds in. Or, to only play the first minute of the video, you would specify #t=,00:01:00. You need to make sure Range Requests are supported by your server: check for Accept Ranges: bytes. It's on by default for Apache and many other servers, but worth checking.


HTML Video Formats

Video File Format Media Type
.mp4 Video/mp4
.ogg video/ogg
.webM video/webM

Video tag attributes tutorial

HTML Video Tag has various attributes to manage the video content. These attributes are not necessary to use but they provide better control over the video playback. For example: enabling autoplay of video, adding video thumbnail, etc. Have a look at the list of attributes supported by video tag:

Element-Specific Attributes

HTML Video Attributes List

Video Tag Description
height It is used to set the height of the video player.
Specifies the height, in pixels, to display the video.
width It is used to set the width of the video player.
Specifies the width, in pixels, to display the video.
poster Poster specifies the image which will work as a thumbnail until the video is loaded completely on the webpage. Just specify the address of the image you want to use as poster.
autoplay It specifies that the video will start playing as soon as it is ready. Specifies whether or not to start playing the video as soon as it can do so without stopping.

This attribute is a boolean attribute. Therefore, the mere presence of this attribute equates to a true value. You can also specify a value that is a case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace (i.e. either autoplay or autoplay="autoplay").

  • Possible values:
    • [Empty string]
    • autoplay

mediagroup

For synchronizing playback of videos (or media elements). Allows you to specify media elements to link together. The value is a string of text, for example: mediagroup=movie. Videos/media elements with the same value are automatically linked by the user agent/browser.

An example of where the mediagroup attribute could be used is where you need to overlay a sign-languge interpreter track from one movie file over the top of another.

controls

Specifies whether or not to display video controls (such as a play/pause button etc). This attribute is a boolean attribute. Therefore, the mere presence of this attribute equates to a true value. You can also specify a value that is a case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace (i.e. either controls or controls="controls").

loop

It is used to play the video on loop i.e., video will start over again every time from the start when it is completed. Just add this as an attribute without any value it will still work. You can also use it like this loop="loop"

preload It specifies the author view to upload video file when the page loads. It is ignored if autoplay is used. Specifies whether the video should be preloaded or not, and if so, how it should be preloaded. This attribute allows the author to provide a hint to the browser/user agent about what the author thinks will lead to the best user experience. This attribute may be ignored in some instances. For example, if the user has disabled preloading or if there are network connectivity issues.
  • Possible values:
    • none : Hints to the browser that the user likely will not watch the video, or that minimizing unnecessary traffic is desirable.
    • metadata : Hints to the browser that the user is not expected to need the video, but that fetching its metadata (dimensions, first frame, track list, duration, and so on) is desirable.
    • auto : Hints to the browser that optimistically downloading the entire video is considered desirable.

Note that the autoplay attribute can overrride the preload attribute (since if the media plays, it naturally has to buffer first, regardless of the hint given by the preload attribute). Despite this, you can still provide both attributes.

mute

Controls the default state of the video's audio output. If present, this attribute results in the audio output being muted (i.e. there is no sound) upon loading. This attribute will override the users' preferences. The user can then choose to turn on the sound if he/she so wishes. This helps users from being annoyed by loud sounds coming from the video as soon as the page/video starts loading. Users often close their browser when this happens. The 'mute' attribute aims to overcome this issue by having the video start off silently instead of loudly.

This attribute is a boolean attribute. Therefore, the mere presence of this attribute equates to a true value. You can also specify a value that is a case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace (i.e. either muted or muted="muted").
  • Possible values:
    • [Empty string]
    • muted
src It specifies the source URL of the video file.

Global Attributes

The video tag accepts the following global attributes. These attributes are standard across all HTML 5 tags.

Video Tag Description
accesskey Specifies a shortcut key that can be used to access this <video> element.

Possible values.

[Any string of characters. This string of characters specifies the key/s the user needs to use in order to access the element.]

class This is a document wide identifier. It is used to refer to a class that is specified in the style sheet. The value should match the name of the class you wish to use.
contenteditable This attribute specifies whether the user can edit the content or not.

Possible values:

  • true
  • false
contextmenu The contextmenu attribute sets a context menu for an element. The value must be the ID of a menu element in the DOM.
dir Specifies the direction of the text.

Possible values:

ValueDescription
ltrSpecifies that the text should read left to right.
rtlThe text should read right to left.
autoThe text direction should be determined programatically using the contents of the element.
draggable It enables the user to drag the <video> element. Just add this attribute within the tag and use the drag feature.

Its possible values are:

  • true
  • false
  • auto
ValueDescription
trueIt enables the element's draggable property.
falseIt disables the draggable property.
autoIt settles with the default value of the browser.
dropzone The dropzone attribute specifies what should happen when the user "drops" an element (i.e. after dragging it) onto this <video> element.

Must be an unordered set of unique space-separated tokens that are ASCII case-insensitive.

Possible values:

ValueDescription
copyResults in a copy of the dragged data. Default value.
moveResults in the data being moved to the new location.
linkResults in a link to the original data.
Any keyword with eight characters or more, beginning with the an ASCII case-insensitive match for the string "string:"Specifies that items with the drag data item kind Plain Unicode string and the drag data item type string set to a value that matches the remainder of the keyword are accepted.
Any keyword with six characters or more, beginning with an ASCII case-insensitive match for the string "file:"Allows you to specify which file types can be processed (i.e. copied, moved or linked) in this dropzone. Example: dropzone="copy file:image/png file:image/gif file:image/jpeg"

Note that this attribute must not have more than one of the three feedback values (copy, move, and link) specified. If none are specified, the copy value is implied.

hidden The hidden attribute as the name suggests is used to hide nay element. You can use this element with <video> tag.
id The id attribute is a document wide identifier, which is used in conjunction with CSS and JavaScript. The value must match the name of the id you wish to use.
itemid The itemid provides a global identifier for an "item". This attribute is optional, however if it is provided, it must have a value that is a valid URL potentially surrounded by spaces.

The itemid attribute can only be present in elements that include both the itemscope and the itemtype attributes, as long as the itemtype attribute specifies a vocabulary that supports global identifiers for items, as defined by that vocabulary's specification.

itemprop This attribute provides one or more properties to one or more "items".

Although this attribute is optional, if used it must have a value that is an unordered set of unique space-separated tokens that are case-sensitive, representing the names of the name-value pairs that it adds. The attribute's value must have at least one token. Each token must be one of the following:

  • A valid URL that is an absolute URL, or
  • If the item is a typed item: a "defined property name" allowed in this situation according to the specification that defines the relevant types for the item, or
  • If the item is not a typed item: a string that contains no U+002E FULL STOP characters (.) and no U+003A COLON characters (:).

Also, Specifications that introduce defined property names that are not absolute URLs must ensure all such property names contain no U+002E FULL STOP characters (.), no U+003A COLON characters (:), and no space characters.

itemref This attribute is used in conjunction with the itemscope attribute, the itemref attribute provides a list of additional elements to crawl to find the name-value pairs of the "item". Although the itemref attribute is optional, if specified, it must have a value that is an unordered set of unique space-separated tokens that are case-sensitive, consisting of IDs of elements in the same home subtree. Also, the itemref can only be used on elements that also have the itemscope attribute present.

itemscope HTML5 elements that have the itemscope attribute create a name-value pair called an "item". Elements with an itemscope attribute may also have an itemtype attribute specified, to give the item types of the item.

This is a boolean attribute. If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace (i.e. either itemscope or itemscope="itemscope").

Possible values:

  • [Empty string]
  • itemscope
itemtype This attribute provides an item type for elements containing the itemscope attribute. The attribute is optional but if it is specified, it must have a value that is an unordered set of unique space-separated tokens that are case-sensitive, each of which is a valid URL that is an absolute URL, and all of which are defined to use the same vocabulary. The attribute's value must have at least one token.

The itemtype attribute must only be present in elements that include the itemscope attribute.

lang Sets the language code to be used.

Possible values:

[Must be a valid RFC 3066 language code, or an empty string.]

spellcheck Specifies whether the element should have its spelling checked.
ValueDescription
[Empty string]The element should have its spelling checked.
trueThe element should have its spelling checked.
falseThe element should not have its spelling checked.

If this attribute is missing, the element will use the default behavior, possibly based on the parent's own spellcheck state.

style Specifies inline styles for this <video> element. This allows you to define the styles within the page, and within this <video> tag, as opposed to referring to styles defined elsewhere (such as an external style sheet). Although this can be useful for over-riding external styles, it is usually preferrable to use external styles in conjunction with the class attribute and/or the id attribute.
tabindex Helps determine the tabbing order for this <video> element (for when the user uses the "tab" key on their keyboard to "tab" through the elements on the page in order to select an element).

Possible values:

[Any valid integer. For example, 0, 1, 2, 3, ...etc]

title It specifies a title to the <video> element. Whenever a user hovers over this element then the specified title will be shown which will look like a tool tip.
translate Determines whether the element's attribute values and the values of its Text node children are to be translated when the page is localized, or whether to leave them unchanged.

The translate attribute is an enumerated attribute and may contain the following possible values:

  • [Empty String]
  • yes
  • no

If the translate attribute is provided, but its value is missing or is invalid, the element will inherit its value from its parent element.


Event Handler Content Attributes

Event handler content attributes enable you to invoke a script from within your HTML. The script is invoked when a certain "event" occurs. Each event handler content attribute deals with a different event.

Here are the standard HTML 5 event handler content attributes.

Video Tag Description
onabort Invoked when an event has been aborted. For example, the browser stops fetching media data before it is completely downloaded.
onblur User has left the focus of the element.
oncancel cancel event handler.
oncanplay Invoked when the browser/user agent can start playing media, but hasn't yet, due to buffering. In other words, if playback were to begin now, it wouldn't play right to the end (due to the current playback rate) - it would need to pause during playback in order to load the rest of the media.
oncanplaythrough The browser/user agent estimates that if playback were to begin now, the media resource could be rendered at the current playback rate all the way to its end without having to stop for further buffering.
onchange User has changed the object, then attempts to leave that field (i.e. clicks elsewhere).
onclick Invoked when the user clicked on the object.
onclose close event handler.
oncontextmenu Invoked when a context menu has been triggered.
oncuechange cuechange event handler.
ondblclick Invoked when the user clicked twice on the object.
ondrag Invoked when an element is being dragged.
ondragend Invoked when an element has stopped being dragged.
ondragenter Invoked when an element has been dragged to a drop target.
ondragexit dragexit event handler.
ondragleave Invoked when an element leaves a valid drop target.
ondragover Invoked when an element is being dragged over a valid drop target.
ondragstart Invoked when a drag operation has started.
ondrop Invoked when an element is being dropped.
ondurationchange Invoked when the length of the media is changed (i.e. the duration attribute has just been updated).
onemptied Invoked when a media resource element suddenly becomes empty (for example, due to a network error).
onended Invoked when the media has reached the end.
onerror Invoked when an error occurs while the element is being loaded. Also handler for script error notifications.
onfocus Invoked when the focus is on the element.
oninput input event handler.
oninvalid invalid event handler.
onkeydown Invoked when a key was pressed over an element.
onkeypress Invoked when a key was pressed over an element then released.
onkeyup Invoked when a key was released over an element.
onload The element has loaded.
onloadeddata Invoked when the browser/user agent can render the media data at the current playback position for the first time.
onloadedmetadata Invoked when the browser/user agent has just determined the duration and dimensions of the media resource.
onloadstart Invoked when the browser/user agent has started loading the media resource.
onmousedown The cursor moved over the object and mouse/pointing device was pressed down.
onmousemove The cursor moved while hovering over an object.
onmouseout The cursor moved off the object
onmouseover The cursor moved over the object (i.e. user hovers the mouse over the object).
onmouseup The mouse/pointing device was released after being pressed down.
onmousewheel Invoked when the mouse wheel is being rotated.
onpause Invoked when the media resource has been paused.
onplay Invoked when the media resource starts playback.
onplaying Playback has begun.
onprogress The browser/user agent is fetching media data the.
onratechange Invoked when the playback rate has changed (i.e. either the defaultPlaybackRate or the playbackRate has just been updated).
onreset reset event handler.
onresize resize event handler.
onscroll scroll event handler. Invoked when the element's scrollbar is being scrolled.
onseeked Invoked when the seeking IDL attribute changed to false (i.e. the seeking attribute is no longer true)
onseeking Invoked when the seeking IDL attribute changed to true and the seek operation is taking long enough that the user agent has time to fire the event.
onselect Invoked when some or all of the contents of an object is selected. For example, the user selected some text within a text field.
onshow show event handler.
onstalled Invoked when the browser/user agent is trying to fetch media data but the data has stalled (i.e. the data has stopped coming).
onsubmit User submitted a form.
onsuspend The browser/user agent is (intentionally) not currently fetching media data, but has not yet downloaded the entire media resource (i.e. it has suspended the download).
ontimeupdate Invoked when the media's current playback position changed.
onvolumechange Invoked when either the volume attribute or the muted attribute has changed.
onwaiting The next frame of the media is not yet available (but the browser/user agent expects it to become available).

HTML Video - Methods, Properties, and Events

HTML5 defines DOM methods, properties, and events for the <video> element. These Properties and Methods allows you to load, play, and pause videos, as well as setting duration and volume. The HTML5 <video> element specifies a standard way to embed a video in a web page.

The type attribute defines the format of the video file used.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> HTML Video Tag Advance </title>
</head>
<body>
<div style="text-align:center">
<button onclick="playPause()">Play/Pause</button>
<button onclick="makeBig()">Big</button>
<button onclick="makeSmall()">Small</button>
<button onclick="makeNormal()">Normal</button>
<br><br>
<video id="video" width="420">
<source src="html-video.mp4" type="video/mp4">
<source src="html-video.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video>
</div>
</html>

Script File

<script>
var myVideo = document.getElementById("video");
function playPause() {
if (myVideo.paused)
myVideo.play();
else
myVideo.pause();
}
function makeBig() {
myVideo.width = 560;
}
function makeSmall() {
myVideo.width = 320;
}
function makeNormal() {
myVideo.width = 420;
}
</script>

HTML5 Video Tip:

  • If you're using the <source> element, we recommend you to add the type attribute to it. This way, the browser can immediately skip a format it doesn't support without trying to play it and wasting resources.
  • By including a poster attribute, you can add an image to be displayed before the video starts.
  • You can style your HTML5 video player using CSS – e.g., you may modify the opacity or set borders.

HTML5 Video Attributes

Tags Description
<video> It defines a video or movie.
<source> It defines multiple media resources for media elements, such as <video> and <audio>
<track> It defines text tracks in media players.

Browser Support

Element
Microsoft Edge browser.png Edge
Chrome browser.png Chrome
Firefox browser.png Firefox
Opera browser.png Opera
safari browser.png Safari
.mp4
Yes
Yes
Yes
Yes
Yes
.ogg
No
Yes
Yes
Yes
No
.WebM
No
Yes
Yes
Yes
No











Follow Us:


Attributes that can be used with the “video” tag are listed below : Autoplay : It tells the browser to immediately start downloading the video and play it as soon as it can. Preload : It intends to provide a hint to the browser about what the author thinks will lead to the best user experience. Loop : It tells the browser to automatically loop the video. height & width : It sets the width and height of the video in CSS pixels. Controls : It shows the default video controls like play, pause, volume etc. Muted : It mutes the audio from the video. Poster : It loads an image to preview before the loading of the video.