veili_13
veili_13

Reputation: 73

Function working differently every reload

I know this sounds a bit weird but I have function that changes the height and width of images and I execute it on document ready. But every time I refresh the page I get different results for the same images (it gets them right every 4th or 5th time). Here is my code:

$("img").each(function(){
    $(this).width(
      parseInt($(this).width()) / (parseInt($(this).width())/parseInt($(".container").css("height")))
    );
    $(this).height(parseInt($(".container").css("height")));
});

The images are in a container and I want them to have the same height as the container and the width changed equally as the height. The height of the container is changed dynamically and every time I change the size of the container I also change the size of the image (I don't have the problem here). I don't quite understand how can this work differently every time I load my page.

Upvotes: 0

Views: 88

Answers (2)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324630

You don't need to wait for images to load.

But you do at least need to wait for them to start loading.

What's the difference? Well, in all image formats that I'm aware of, one of the first pieces of metadata is the image's dimensions. This is why with bigger images you can see the browser reserve the space as soon as the image has started loading, and then fills it in with the image as it loads.

So! With this in mind, let's get your page looking as sharp as possible, shall we?


Forget all that, I've just realised, you're setting the height to the height of the container? In that case...

$("img").each(function(){
    this.style.width = "auto";
    this.style.height = "100%";
});

There you go. Using auto for the width will keep the aspect ratio.

Upvotes: 0

Gatekeeper
Gatekeeper

Reputation: 1616

You should wait for all images to load using $(window).load() function, or use some other way to controll your images loading. Choose your way but the problem is simply that your function gets fired before images are loaded.

Upvotes: 1

Related Questions