Learn how to retrieve the dimensions of a video loaded through the HTML5 video player.

In different situations, you may need to retrieve the dimensions of a video with JavaScript on your website (not from the container of the video, but the video itself). This can be easily done when you load the video on a video tag:

var videoElement = document.getElementById("video");

// Print the native height of the video
console.log(videoElement.videoHeight);

// Print the native width of the video
console.log(videoElement.videoWidth);

You need to know however that this information can't be obtained immediately when the page has been loaded, it will probably return null, because the video has not been loaded yet. So, if you want to do this right, you will need to attach an event listener to the video element, specifically the loadedmetadata event. The loadedmetadata event occurs when metadata for the specified audio/video has been loaded. Metadata for audio/video consists of: duration, dimensions (video only) and text tracks. You can attach the event listener like this:

var videoElement = document.getElementById("video");

videoElement.addEventListener('loadedmetadata', function(e){
    // Print the native height of the video
    console.log(videoElement.videoHeight);

    // Print the native width of the video
    console.log(videoElement.videoWidth);
});

Note that this will force your code to become asynchronous, so you may want to wrap this code using Promises or convert it into an asynchronous function if you don't like to work with callbacks.

Happy coding ❤️!


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors