Run
Run

Reputation: 57176

jQuery gets the image height before the image is loaded?

I have looked around and tried many solutions, but jquery still tries to get the image height before the image is loaded:

$('img').load(function(){
    var heightStart = $(".carousel .carousel-inner img").height();
    alert(heightStart); // 0
});

I always get an 0. Any ideas what is the best way of doing this?

I even have tried with the plain js:

    var i = new Image()
    i.src = "images/xxx.jpg";
    var h = i.height
    alert(heightStart); // 464

It gets the image height but the number is wrong! The number is always smaller but the image has a long height.

EDIT:

the images have not height and width attributes:

<div id="myCarousel" class="carousel slide" data-ride="carousel">

    <div class="carousel-inner">

    <div class="item active">

        <img class="first-slide" src="images/xxx.jpg" alt="First slide" class="img-responsive">
        <div class="container">
            <div class="carousel-caption">xxx</p>
                </div>
            </div>
        </div>
    </div>

My image height is 464 so new Image() is correct. but the problem is that the image has been resized on the large screen with img-responsive.

Upvotes: 0

Views: 194

Answers (1)

php_nub_qq
php_nub_qq

Reputation: 16017

$('img').load(function(){
    alert($(this).height());
});

or

var i = new Image()
i.src = "images/xxx.jpg";
i.onload = function() { alert(this.height) };

A little explanation to go with the answer - your first function registers onload listeners to all present img elements that alerts the first matched img element within .carousel .carousel-inner's height, which might be 0, who knows.

The problem with your vanilla example is that you are trying to alert the height before the image is done loading.

Upvotes: 3

Related Questions