Reputation: 678
My company's new web layout depends on an image being 150px wide. The previous design required the images to be 125px tall. So all the images have different widths based on their width/height ratio. I put some javascript together to resize the images to fit in their space until our interns get around to sizing the images in photoshop. My temporary solution seems to work fine in everything but ie8, including ie6 of all things! Here's the code.
$('div.item > div.left > a > img').load(function(){
var img = $(this);
img.each(function(){
var width = img.width();
var height = 125;
var ratio = width/height;
if(width > 150){
var newWidth = 150;
var newHeight = newWidth/ratio;
img.attr({width:newWidth, height:newHeight});
}
});
});
Any thoughts are greatly appreciated
Upvotes: 0
Views: 1125
Reputation: 11
Sometimes the images are chached by browser and load event is not called. Try changing image sizes on 'each' event in that case. Chrome and browsers IE > 9 can cache images with proper sizes but IE <= 8 can't do that. So I included conditional resizing of images for IE <= 8.
Add the following to your page:
<!--[if lt IE 9]>
<script type="text/javascript">
$('div.item > div.left > a > img').each(function(){
var img = $(this);
img.each(function(){
var`enter code here` width = img.width();
var height = 125;
var ratio = width/height;
if(width > 150){
var newWidth = 150;
var newHeight = newWidth/ratio;
img.attr({width:newWidth, height:newHeight});
}
});
});
</script>
<![endif]-->
Upvotes: 1
Reputation: 818
I've had the same problem.
I solved it with this :
$(window).load(function() {
....
});
It seems working in my web site.
Upvotes: 0
Reputation: 788
You should try to work on the image object itself
$('div.item > div.left > a > img').load(function(){
var img = $(this)[0];
img.each(function(){
var width = img.width();
var height = img.height();
var ratio = width/height;
if(width > 150){
var newWidth = 150;
var newHeight = newWidth/ratio;
img.width(newWidth);
img.height(newHeight));
}
});
});
Upvotes: 0
Reputation: 26183
Change
img.attr({width:newWidth, height:newHeight});
to
img.css({width:newWidth+'px', height:newHeight+'px'});
and it should work as you wish.
Upvotes: 0