0
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?

natlee75
  • 5,097
  • 3
  • 34
  • 39

2 Answers2

1

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.

alexander farkas
  • 13,754
  • 4
  • 40
  • 41
0

If you want to get the intrinsic width and height of the video element, you should get the videoWidth and the videoHeight. See this documentation

Sanghyun Lee
  • 21,644
  • 19
  • 100
  • 126