Reputation: 8426
I have square DIV and large portrait and landscape images.
I need to fit the image in a DIV with the extra part going overflow:hidden
For eg. If portrait set width=width of div height:auto
Opposite for Lanscape.
I tried this script but it didn;t work
$('.magic').each(function(){
if($(this).css('width')>$(this).css('height')){
$(this).css('height', '300px');
$(this).css('width', 'auto');
}
else{
$(this).css('width', '300px');
$(this).css('height', 'auto');
}
});
PS Images can't stretch and must scale
Upvotes: 3
Views: 9178
Reputation: 1885
Use some CSS like this
.magic.portrait {
height: 300px;
width: auto;
}
.magic.landscape {
width: 300px;
height: auto;
}
and just add a class with your JS
$('.magic').each(function(){
if($(this).width() > $(this).height()){
$(this).addClass('landscape');
}else{
$(this).addClass('portrait');
}
});
This also helps keep your application logic and styles nicely separated. Even better, add these classes server side, and avoid the JavaScript altogether.
Upvotes: 5
Reputation: 4394
If you really want a javascript/jquery solution, have a look at jQuery AnyStretch plugin. It just does what you want.
Upvotes: 1
Reputation: 707158
If image sizes are known in advance, you could do this all with CSS.
If you decide you must use javascript, then the problem with your current code is that $(this).css('width')
retrieves a string like "300px"
, not a number thus the comparison of two strings doesn't work properly like you would expect a numeric comparison to work.
You can either convert it to a number or you can just use $(this).width()
which returns a number in pixels.
Working example:
$('.magic').each(function(){
var self = $(this);
var width = self.width();
var height = self.height();
if (width > height) {
self.css({height: "300px", width: "auto"});
} else {
self.css({width: "300px", height: "auto"});
}
});
Demo: http://jsfiddle.net/jfriend00/B7hVp/
Upvotes: 0