How can I get the html5 video element's width and height
26,080
$(function () {
$("#video").bind("loadedmetadata", function () {
var width = this.videoWidth;
var height = this.videoHeight;
// ...
});
});
Author by
hh54188
Updated on August 30, 2020Comments
-
hh54188 over 3 years
I have a simple html5 video tag:
<video autobuffer="true" id="video" controls="true"> <source src="some_url"></scource> </video>
I have not define a obvious width and height in video tag or in css,the video wrapper would adjust according to the source video size,the problem is, how can I get the video current width and height? I have tried jquery
$('video').css('width');
but it return me the origin size :300px
what I see in the page is 800px!
How can I solve this problem?
-
Admin over 10 yearsIt looks like this will only work if you add the function before the video is loaded. Is there a general way to get these values for a video that is already playing?
-
Admin over 10 yearsBummer. Thanks, though.
-
Neil over 10 yearsWhat is stopping you from adding it before your video? It just sits there listening for the loadedmetadata event.
-
Admin over 10 yearsI can do that, but it's still a bummer that it's necessary to prepare to ask for such a basic thing. It'd be like having to install callbacks ahead of time to be ready to ask a div what children it has.
-
Konstantin about 8 yearsI believe you can use videoHeight/videoWidth anytime AFTER metadata are loaded. The catch there is not to call it before metadata is loaded, and depending on loadedmetadata event is a simpliest way to ensure it's not too early to call those properties.
-
Nateowami over 7 yearsUm, according to the docs,
innerWidth()
willGet the current computed inner width (including padding but not border)
. Granted, most videos do not use padding, but you could just as easily get the video element's dimensions withvideo.width
andvideo.height
. That would give the true value (i.e. no padding), is simpler, and doesn't use jQuery. It's important to distinguish between the dimensions of the video element and the video's native dimensions though. What this answer and the one above are finding are completely different.