HTML5 Video Dimensions

Elliot picture Elliot · Nov 9, 2010 · Viewed 92.6k times · Source

I'm trying to get the dimensions of a video of which I'm overlaying onto a page with JavaScript, however it is returning the dimensions of the poster image instead of the actual video as it seems it's being calculated before the video is loaded.

Answer

natlee75 picture natlee75 · Feb 17, 2012

It should be noted that the currently accepted solution above by Sime Vidas doesn't actually work in modern browsers since the videoWidth and videoHeight properties aren't set until after the "loadedmetadata" event has fired.

If you happen to query for those properties far enough after the VIDEO element is rendered it may sometimes work, but in most cases this will return values of 0 for both properties.

To guarantee that you're getting the correct property values you need to do something along the lines of:

var v = document.getElementById("myVideo");
v.addEventListener( "loadedmetadata", function (e) {
    var width = this.videoWidth,
        height = this.videoHeight;
}, false );

NOTE: I didn't bother accounting for pre-9 versions of Internet Explorer which use attachEvent instead of addEventListener since pre-9 versions of that browser don't support HTML5 video, anyway.