8

I am trying to get width and height of tag, I am using the following markup:

<div class="masked" id="video_container">
    <video id="video" loop="loop" muted="muted" tabindex="0" style="width: 100%; height: 100%;">
        <source src="..." type="..."</source>
        <source src="..." type="..."</source>
    </video>
</div>

The key part is that width and height attributes are both set to 100%, and when window is changed aspect ratio of video is saved, but I cannot get it's actual width and height.

I tried to get value using offsetWidth and offsetHeight properties, but they are return actual size of the video.

Edit:

This is the piece of code that working for me:

var videoActualWidth = video.getBoundingClientRect().width;
var videoActualHeight = video.getBoundingClientRect().height;

var aspect = videoActualWidth / videoActualHeight;

if (w / h > aspect) {
    video.setAttribute("style", "height: 100%");
} else {
    video.setAttribute("style", "width: 100%");
}

Thanks!

Kristian Vitozev
  • 5,791
  • 6
  • 36
  • 56
  • Do you mean that, once the page has loaded and the width and height established (no matter what the browser dimensions) you want the video to keep those original dimensions, even if the browser width and/or height change? – ralph.m Apr 29 '13 at 08:06
  • Hello, I have one video and both width and height properties are set to 100% via CSS. My parent container is full-width. My video is responsive this way, when I resize browser window it keeps it's aspect ratio and show white stripes on sides. But in DOM my video element get width of a whole available space, although visible it's smaller. Sorry for my bad explanation, later today I will setup new jsfiddle. – Kristian Vitozev Apr 29 '13 at 09:21

1 Answers1

18

This code will give you the dimensions of the video tag (not the dimensions of the video itself)

var video = document.getElementById("video");
var videotag_width = video.offsetWidth;
var videotag_height = video.offsetHeight;

This code will give you the dimensions of the video that is currently playing

var video = document.getElementById("video");
var video_height = video.videoHeight;
var video_width = video.videoWidth;
pants
  • 192
  • 13
Karim Lee
  • 41
  • 1
  • 4
  • 5
    Important to note that `video.videoWidth` gives the video's intrinsic dimensions in CSS pixels. If the video is scaled at all, it won't be the same as the element's dimensions. Neither do the element's dimensions necessarily equal the dimensions of the video as it is shown, since by default it will scale to fit inside the element. Not being able to find an answer for this I devised a solution ([calculate dimensions based on difference in aspect ratio](https://nathanielpaulus.wordpress.com/2016/09/04/finding-the-true-dimensions-of-an-html5-videos-active-area/)). (Disclosure: that's my blog). – Nateowami Sep 05 '16 at 08:05