southpaw93
southpaw93

Reputation: 1961

Getting the height of an image in javascript

I have this image : <img style="border-bottom-right-radius:0px;" id="cover_image" src="Daft+Punk+Tron+Legacy.jpg" alt="cover" width="851" /> , I have set the width of the image and the photo automatically keeps aspect ratio and resize both width to 851 and height to a certain value, I want to grab the height value with Javascript but it's not working

So far I have tried this:

$(document).ready(function() {
    alert($("#cover_image").height());
});

When I try

$(document).ready(function() {
        alert($("#cover_image").width());
    });

it works and it shows 851 which is the correct value of the width, but when I use height is returns 0.. can you point me in the right direction please ?

Upvotes: 0

Views: 85

Answers (2)

Arun Bertil
Arun Bertil

Reputation: 4638

clientWidth and clientHeight are DOM properties that show the current in-browser size of the inner dimensions of a DOM element (excluding margin and border). So in the case of an IMG element, this will get the actual dimensions of the visible image.

var img = document.getElementById('imageid'); 
//or however you get a handle to the IMG
var width = img.clientWidth;
var height = img.clientHeight;

Thanks AB

Upvotes: 1

A. Wolff
A. Wolff

Reputation: 74420

Use onload event of the image:

$("#cover_image").on('load',function(){
    if(this.complete) alert($(this).height());
});

Upvotes: 2

Related Questions