Search code examples
javascriptwidthhtml5-videocomputed-stylegetproperty

How do I reliably and consistently get the calculated width style for a VIDEO element?


var vid = document.createElement("video");
vid.src = "big_buck_bunny_640x360.mp4";
document.getElementsByTagName("body")[0].appendChild(vid);
console.log(window.getComputedStyle(vid, null).getPropertyValue("width"));

The console invariably shows "300px," but obviously the value I'm looking for is "640px". If I use setTimeout on that console.log call with a delay of 100 milliseconds, the correct "640px" value shows up in the console.

I'd rather not use setTimeout, though. Is there a "proper" way to get the accurate calculated style value?


Solution

  • You can get the correct videoHeight/videoWidth after the event loadedmetadata or if the readyState property is higher or equal 1.

    The code to get the right value - using jQuery - could look like this:

    $('<video />')
        .appendTo('body')
        .one('loadedmetadata', function(){
            console.log( $.prop( this, 'videoHeight'), $.prop( this, 'videoWidth') );
        })
        .prop({
            'src': 'big_buck_bunny_640x360.mp4',
            'preload': 'metadata'
        })
    ;
    

    But note, that, not all browser do start fetching the video immediately.