I\'d like to use the dimensions of a HTML5 video element in JavaScript. The video
-tag itself does not have any dimensions set, so I expect it to scale to the size o
TL;DR Adding loadedmetadata
listener after DOMContentLoaded
will not guarantee the listener will be added before loadedmetadata
event is fired, however, adding the event listener to an element created before the video element with src
(e.g. document
) and in capture phase or adding the event listener to the video element inline as an attribute will.
The dimensions of the video file will be loaded with the video file metadata. So you will need to wait loadedmetadata
event to be fired then you will be able to get dimensions from videoWidth
and videoHeight
properties of the html video element, where they will be set and ready, these you got all correct.
Note for DOMContentLoaded
: Adding the event listener after the dom content loaded event will only guarantee the exsitence of the html element in first place to be able to add an event listener on. That is the correct method of doing that thing and here it is not the issue. On the contrary, it is the cause that the issue in question has been run into: The element's existence, with a src
attribute to load data, before the event listener added is kind of sort of the reason event listener is prone to miss the event it should catch and handle.
By the time you add this event listener to the video element, the event might have already happened, propagated and ended, since you add the event handler after the video element created with its src
attribute. It will start loading video hence video metadata. If it is slow enough to do that your code will get a chance to be added to the video element before loadedmetadata
event ended after video metadata has been loaded.
You need to register the event handler before the video
element starts loading its video file. Here it is by with src
attribute, so you need to add the handler before or same time you
add the src
attribute.
You can add an inlined event attribute on the video element itself:
. Here
not sure if the handler should be defined inline too or just
referencing work too.
You can add the event listener before the video element is created with a src
attribute. That means you need to add it to another ancestor html element that is created before the video element is created wth a src
attribute. Also that event does not bubble but captures. So, you have to add it for capture phase of the event and to a ancestor element, e.g. document
.
document.addEventListener("loadedmetadata", function(e){
// if necesssary one can add custom logic here for example to check if the event target is the element we are listening the event for with event.target
var video = e.target;
var dimensions = [video.videoWidth, video.videoHeight];
alert(dimensions);
}, true);