Getting Intrinsic HTML5 Video Dimensions

Tuesday, November 29, 2011

The HTML 5 DOM interface for a video element allows you to get the underlying video's width and height in pixels, but, be careful not to ask for the dimensions too early. If you ask as soon as the DOM is ready, like in the following code, you'll probably see width and height as 0.

$(function () {

    var video = $("#video").get(0);
    var width = video.videoWidth;
    var height = video.videoHeight;

    // ...
});

You'll want to wait for the video element to raise the loadedmetadata event before asking for the dimensions. The event is documented as firing when "the user agent has just determined the duration and dimensions of the media resource and the text tracks are ready".

Example:

$(function () {

    $("#video").bind("loadedmetadata", function () {
        var width = this.videoWidth;
        var height = this.videoHeight;
        // ...
        
    });

});

Comments
Comments are now closed.
by K. Scott Allen K.Scott Allen
My Pluralsight Courses
The Podcast!