akmur
akmur

Reputation: 1635

Alternative to setTimeout for images

If I want to create a div that is as high a (responsive) image using javascript, I am resorting to setTimeout. For example I might have code like this

setTimeout(function(){
    var $imgheight = $('img').height();
    $('.mydiv').height($imgheight);
}, 400);

Is there any alternative to this? I know about imagesloaded plugin, is there any simpler alternative?

Many thanks

Upvotes: 0

Views: 88

Answers (2)

filur
filur

Reputation: 1556

You can use the load event to know when the images are loaded:

$('img').on('load', function(){
    $('.mydiv').height(this.height);
});

http://jsfiddle.net/083d89me/

Though I don't see the need to set the divs height. Doesn't it adjust itself to the image height by default?

Upvotes: 1

Lashus
Lashus

Reputation: 399

Well you don't want to create a new div just to change the height of the existing one so please change the description.

Please use the answer from @filur to set the height according to loaded image and then add eventListener for window.resize event :)

$(window).on('resize', function(){ ... });

Upvotes: 0

Related Questions