Paul Schneider
Paul Schneider

Reputation: 325

Get the original dimensions of a <video>

I'm trying to have a list of videos and pictures, each resized to the same size for easier view.

when the user clicks on one of them, they should be resized to their original size (or that of the bounding box at max)

My problem is: how do i get the ORIGINAL dimensions of a video?

for images,

var img = new Image();
img.src= $(event.target).attr("src");
img.width   //this is the width
img.height  //this is the height

works like a charm.

But i can't find a way to do the same for a <video>. is there any at all?

I understand there's something about loading metadata, but the video IS already loaded, i just want to resize it to its original size (well i wouldn't have a problem with them being lazyloaded on resize, but i guess that's more of an effort)

Is it possible to do this? if so, how? jQuery preferred.

SOLUTION:

var video = $(event.target);
var width = video[0].videoWidth;

Upvotes: 6

Views: 11021

Answers (4)

Fuse Gamer
Fuse Gamer

Reputation: 53

Try this

$(function(){
  $('#my_video').bind('loadedmetadata', function(){
    var rawWidth = $(this).prop('videoWidth'); 
    var rawHeight = $(this).prop('videoHeight');
    $("#result").html('Height: '+rawHeight+'; Width: '+rawWidth);  
  });
});

Upvotes: 0

guerrato
guerrato

Reputation: 394

The solutions posted didn't work for me. If anyone has the same issue, my solution may help out.

const video = document.getElementById("myVid")

video.addEventListener('loadeddata', function(e) {
    let width = e.target.videoWidth
    let height = e.target.videoHeight

    let elWidth = e.target.width
    let elHeight = e.target.height

 }, false)

Check it on https://codepen.io/guerrato/pen/aYNeaW

Upvotes: 3

WiRa
WiRa

Reputation: 998

I noticed that until the metadata is loaded you'll get wrong results... if you want to be sure, wait for the metadata loaded event, then get videoHeight and videoWidth!

yourVideoElement.addEventListener( "loadedmetadata", function (e) {
        console.log(this.videoHeight);
        console.log(this.videoWidth);
    }, false );

Upvotes: 0

Amr
Amr

Reputation: 131

You can do that with native Javascript :

var video = $("#myvideo" ); //JQuery selector 
video[0].videoWidth; //get the original width
video[0].videoHeight; //get the original height

To get know too :

video[0].width; //get or set width for the element in DOM
video[0].height; //get or set height for the element in DOM

For more information you can check those links from W3 : videoWidth , videoHeight

Upvotes: 5

Related Questions