The Hawk
The Hawk

Reputation: 1568

Get the Height of an Image

This should be easy but it's not. I just need the height of an image:

<div id="map">
    <img src="myimage.jpg">
</div>
$("#map img").height(); // returns 0

Upvotes: 0

Views: 327

Answers (4)

turbopipp
turbopipp

Reputation: 1255

The problem is that the height or width are not calculated yet, listen to the loading of the image with .on( "load", handler )

$("#map img").on("load", function(){
  var height = $(this).height();
  $('#output').html('height=' + height);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<div id="map">
    <img src="https://via.placeholder.com/400x40">
</div>
<div id="output"></div>

Upvotes: 2

The Hawk
The Hawk

Reputation: 1568

This worked for me:

$(window).load(function () {

    var artLists = [];
    $("ul.articles").each(function (index) {
        var imageHts = [];
        $("li img", $(this)).each(function () {
            imageHts.push($(this)[0].height);
        })
        artLists.push(imageHts);
    })

});

Upvotes: -1

ryanpcmcquen
ryanpcmcquen

Reputation: 6445

Use .clientHeight (pure JavaScript):

https://jsfiddle.net/ryanpcmcquen/v6yz8t3u/

console.log(document.querySelector('img').clientHeight);
<img src="//makelin.us/100/100" />

Read up on it here: https://developer.mozilla.org/en-US/docs/Web/API/Element/clientHeight

Note that this will give you the height as the image appears on the page, it could be affected by CSS.

Note: To get the actual height of the image, use .naturalHeight.
Great article here: https://davidwalsh.name/get-image-dimensions

To make sure this runs after the image has loaded, do:

window.addEventListener('load', function () {
  console.log(document.querySelector('img').clientHeight);
});

Upvotes: 2

Domain
Domain

Reputation: 11808

You can refer following example to get height of image-

<div id="map">
    <img id="img_id" src="http://www.clickerzoneuk.co.uk/cz/wp-content/uploads/2010/10/PuppySmall.jpg" >
</div>

write following code in js file

var height = document.getElementById("img_id").clientHeight;

alert(height);

check example using following link-

http://jsfiddle.net/v60mut3L/1/

Upvotes: 0

Related Questions