How to prevent HTML5 video from changing size when loading a new source

Published May 5, 2020

I wanted to load a new source into my <video> component, but it kept glitching.

<!-- HTML -->
<video id="video">
  <source src="src1.mp4" type="video/mp4">
    Your browser does not support the video tag.
</video>
// JavaScript
let video = document.getElementById("video");
video.src = "src2.mp4";
video.load();

Every time video.load() runs, the video changes its width and height really quickly in between videos, making it look like a glitch.

What’s happening is the video is restoring its default width and height between sources.

In order to prevent this, we can add an event listener to check for when the video metadata is loaded, and then manually set the video player’s width and height to be the client width and height, which is the visual portion of the element (including padding).

// JavaScript
video.addEventListener('loadedmetadata', (e) => {
    let player = e.target;
    player.width = player.clientWidth;
    player.height = player.clientHeight;
});

More JS Articles