Reputation: 14008
I have some code that when the page loads gets the height of an image and then resizes its container div accordingly. This works fine unless its the first time the page has been loaded or i do a hard refresh with ctrl + f5, then it doesn't work. I have tried using
$('#div img').load(function() {
// put the code here
});
But I get the same problem. Anyone know why this is happening?
This is my code:
maxheight = 0;
$('#venue #main-img img').each(function() {
height = $(this).height();
if(height > maxheight) {
maxheight = height;
}
$(this).hide();
});
$('#venue #main-img').animate({ height: maxheight });
$('#venue #main-img img').first().show();
Sorry should have said. The code is within $(document).ready()
Upvotes: 0
Views: 3748
Reputation: 36
I had this same problem as well. After some researching it seems that the browser needs to have a predefined value for the image in order to reset the size. So on the initial load, it messes up, but on reload the height of the image is retained, so then the javascript works correctly. You need to code in the initial height of your images so that the JS can resize them properly.
Upvotes: 2
Reputation: 1858
You could use some jQuery plugin like this one https://gist.github.com/797120/b7359a8ba0ab5be298875215d07819fe61f87399
Upvotes: 0
Reputation: 385108
If your images do not have width/height specified in HTML or CSS, then their width/height is not known until after the images have been downloaded.
$(document).ready
fires when the DOM has been loaded, but potentially before auxiliary media such as images have been downloaded. That means you have a width/height, potentially, of 0 when your browser is re-downloading the images.
Maybe you can use something like this. The "imagesLoaded" plugin in particular looks useful (though its code implies that $(imgs).load
should have worked for you >.<).
Upvotes: 1
Reputation: 18832
Try calling your code in $(window).load
. This will run after all images have loaded.
$(window).load(function () {
// run code
});
Or you could try the imgload
plugin.
Upvotes: 2
Reputation: 5052
You might want to try this instead:
$(document).ready(function(){
//code here
});
Upvotes: 0