Reputation: 1228
I need a script to scale the image to fill the parent container and maintain aspect ratio (plus to work in ie8), therefore I created the code below and it's working ok but the thing is that sometimes that code is creating a border gap over the image, and when you refresh the page it sometimes disappear or reappear...I use copies of this code for more divs...
It goes like this:
SCRIPT:
$(window).bind('resize', function () {
var container_height = $('#homepage').height();
var container_width = $('#homepage').width();
var image_height = $('#homepage img').height();
var image_width = $('#homepage img').width();
if (container_width > image_width) {
$('#homepage img').css({
'width': '100%',
'height': 'auto'
});
} else if (container_height > image_height) {
$('#homepage img').css({
'width': 'auto',
'height': '100%'
});
};
});
$(window).trigger("resize");
CSS:
#homepage{
width:100%;
height:850px;
overflow:hidden;
position:relative;
display:table;
margin:0;
padding:0;
}
#homepage img{
width:auto;
height:100%;
position:absolute;
bottom:0;
right:0;
margin:0;
padding:0;
}
And finally some HMTL:
<div id="homepage">
<img src="img/source.jpg" />
</div>
Upvotes: 1
Views: 569
Reputation: 21
You should always remember to ensure that all images are fully loaded before You start work with them.
Quick solution is to simply trigger 'resize' event after all resources are loaded:
$( window ).load(function() {
$(this).trigger("resize");
});
You could also trigger 'resize', when only Your image will be loaded:
$('#homepage img').on('load', function(){
$(window).trigger("resize");
});
But you should remember about 'IE image caching problem': https://stackoverflow.com/a/12000119
Upvotes: 2