Eugeny89
Eugeny89

Reputation: 3731

$.height returns 0 on first load of page

I'm having the following img on the page

<img class="some-class" src="img/some-img.gif" style="top: 29px; left: 121px;">

In css I have

img.some-class {
    display: inline-block;
    position: absolute;
}

img is located in div having display: inline-block.

When I'm doing console.log($img.height()) it outputs 0 on first load of page (i.e. on first load after opening of browser). Still after I refresh page console.log($img.height()) outputs real value of height of img. What can be a reason of problem?

UPD. please note that an img is added dynamicaly.

Upvotes: 1

Views: 328

Answers (1)

leftclickben
leftclickben

Reputation: 4614

Before the image is loaded, the browser doesn't know the height. When you load the page the second time, the image is already in the browser cache, so it knows the height.

You must place your console.log() call inside a $(window).load() block. This will run after the images have loaded.

$(window).load(function() {
    console.log($('img#myimg').height();
});

If the image is added dynamically, then you can put a load() handler on the image itself:

$('img#myimg').load(function() {
    console.log($(this).height());
});

Load event info:

http://api.jquery.com/load-event/

More info found on Google:

http://web.enavu.com/daily-tip/daily-tip-difference-between-document-ready-and-window-load-in-jquery/

Upvotes: 5

Related Questions