0

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.

Run
  • 54,938
  • 169
  • 450
  • 748
  • Call me crazy but for the first part, shouldn't it be `$(".carousel .carousel-inner img").load`? If you just do `$('img')`, it will call the function even when the first image on the page loads, not just that specific image. Of course, I can't see your HTML, maybe it is the only image on the page... – aaronofleonard Sep 28 '16 at 16:31
  • guys, please see my edit above. thanks. – Run Sep 28 '16 at 16:34
  • Is that all your question about what your title means? If so: http://stackoverflow.com/a/6575319/1414562 – A. Wolff Sep 28 '16 at 16:36
  • @A.Wolff have tried that answer. but still no luck. – Run Sep 28 '16 at 16:45

1 Answers1

3
$('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.

php_nub_qq
  • 15,199
  • 21
  • 74
  • 144