Reputation: 29
I'm trying to set the height of a image to 150px if the image width is larger than the height, and if the image height is larger than the width, the width of the image changes to 150px.
This is my markup:
CSS:
.posts { width:150px; height:150px; }
HTML:
<div class="posts"><img src="image" /></div>
JQUERY SCRIPT:
var photoW = $('.posts img').width();
var photoH = $('.posts img').height();
if( photoW > photoH ){
$(".posts img").css("width", "auto").css("height", "100%");
}
else {
$(".posts img").css("width", "100%").css("height", "auto");
}
It doesn't work and I don't know why. I would appreciate if you could help me.
Upvotes: 1
Views: 140
Reputation: 1279
No offense, but I am not sure what your intent is. A typical instance requirement is to maintain a specific bounding box, say of 150px, around an image. Here is a fiddle that does just that. Notice there is no CSS for width and height, since both are set dynamically. This is the code:
var $photo, w_px, h_px;
$photo = $('.posts img');
w_px = $photo.width();
h_px = $photo.height();
if ( h_px > w_px && h_px > 150 ) {
$photo.css({ height : 150, width : '' });
}
else if ( w_px > 150 ) {
$photo.css({ height : '', width : 150 });
}
If your requirements are instead as you typed them, than this fiddle should do the trick.
Upvotes: 0
Reputation: 388316
The problem could be that when your is executed the image might not have been loaded... so wait for the image to load
Try something like
jQuery(function ($) {
$('.posts img').load(function () {
if (this.width) {
if (this.height > this.width) {
this.style.height = '100%'
} else {
this.style.width = '100%'
}
}
}).filter(function () {
return this.complete
}).trigger('load')
})
Demo: Fiddle
Upvotes: 1
Reputation: 1650
here is fiddle for you, you should run code on document ready
$(document).ready(function(){
var photoW = $('.posts img').width();
var photoH = $('.posts img').height();
if( photoW > photoH ){
$(".posts img").css({width: "auto",height: "100%"});
}
else {
$(".posts img").css({width: "auto",height: "100%"});
}
});
Upvotes: 0