Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery load event on images

I want to resize an image parent to the same size of the image, when the images are loaded.

At this time i'm using this code:

$(window).load(function(){
    $('.image-principale').each(function(){
        $(this).parent().css('height', $(this).height());
    });
});

It work, except than it runs only when every image has loaded. I tried to add an load handler to every image directly but they doesn't trigger.

What's wrong?

Thank you!

like image 862
Hubert Perron Avatar asked Feb 01 '26 00:02

Hubert Perron


1 Answers

Try the following:

...Your HTML...

<script type="text/javascript">
    $('.image-principale').load(function(){
        $(this).parent().css('height', $(this).height());
    });
</script>

Note that the script must be placed after the HTML, or it will run before the <img> elements exist and will not actually do anything.

You could also try using live, like this:

$('.image-principale').live('load', function(){
    $(this).parent().css('height', $(this).height());
});

However, I don't know whether it will actually work.

like image 133
SLaks Avatar answered Feb 02 '26 19:02

SLaks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!