HTML Audio & Video
HTML DOM Video Object
The Video object represents an HTML <video> element in the DOM. It implements the HTMLVideoElement interface, which extends HTMLMediaElement with two extra read-only properties for the intrinsic size of the video: videoWidth and videoHeight. All the playback properties, methods and events of media elements are also available.
Definition and Usage
A Video object lets JavaScript control a video the same way the Audio object controls sound: play, pause, mute, change the playback rate, seek to a time and listen for events. In addition it exposes the natural pixel dimensions of the decoded frames through videoWidth and videoHeight, which stay 0 until enough metadata has loaded.
Syntax
// Access an existing <video> element
let video = document.getElementById("myVideo");
// Create a video element dynamically
let video = document.createElement("video");There is no dedicated new Video() constructor the way there is for Audio, so a dynamic video element is created with document.createElement("video").
Example: play and pause a video
<video id="myVideo" width="320" controls>
<source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<button onclick="toggle()">Play / Pause</button>
<script>
const video = document.getElementById("myVideo");
function toggle() {
if (video.paused) {
video.play();
} else {
video.pause();
}
}
</script>The paused property reports whether playback is currently stopped, so a single button can switch between play() and pause(). Because the element has the controls attribute, the browser also shows its own player UI.
Example: reading the intrinsic size
const video = document.getElementById("myVideo");
video.addEventListener("loadedmetadata", () => {
console.log("Natural size:", video.videoWidth + "x" + video.videoHeight);
console.log("Duration:", video.duration + " seconds");
});videoWidth and videoHeight are the decoded pixel dimensions of the video itself, which may differ from the CSS width and height you set on the element. They are 0 until the loadedmetadata event fires.
