16

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?

hh54188
  • 14,887
  • 32
  • 113
  • 184

2 Answers2

32
$(function () {

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

    });

});
Neil
  • 7,861
  • 4
  • 53
  • 74
  • 1
    It 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? –  Jan 16 '14 at 01:01
  • 1
    Bummer. Thanks, though. –  Jan 16 '14 at 15:03
  • What is stopping you from adding it before your video? It just sits there listening for the loadedmetadata event. – Neil Jan 16 '14 at 16:28
  • 1
    I 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. –  Jan 16 '14 at 16:41
  • 5
    I 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. – Konstantin Apr 17 '16 at 20:18
0

Just found out that we can get the video width and height as:

$("#video").innerHeight();
$("#video").innerWidth();

These two functions are exposed by jQuery.

Another reason why jQuery rocks!!!

Shantanu Wagh
  • 1,011
  • 7
  • 13
  • 3
    Um, according to [the docs](https://api.jquery.com/innerwidth/), `innerWidth()`will `Get 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 with `video.width` and `video.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. – Nateowami Sep 05 '16 at 07:36