Reputation: 2059
#foo {width: 300px; height: 400px; overflow: hidden;}
<div id="foo"></div>
this.someimage = randomImageUrl;
$("foo").innerHTML = "<img src='"+this.someimage+"' class='fooimage' />";
Now, the picture could be 200x200 or 1100x400 ... it's totally random. I can just stretch it (or reduce its size) by using:
.fooimage {width: 300px; height: 400px;}
$("foo").innerHTML = "<img src='"+this.someimage+"' class='fooimage' />";
Or I could test its size:
imgHeight = newImg.height;
imgWidth = newImg.width;
... and maybe something like this:
if(imgHeight >400){
$("foo").innerHTML = "<img src='"+this.someimage+"' height='400' />";
}
and browsers will do the rest.
But there must be something better. Any ideas? Thanks! :)
Upvotes: 1
Views: 414
Reputation: 16373
You might want to try this:
$(window).load(function () {
if ($('#my_image').width() > 300) {
$('#my_image').css({'width':'300px'});
}
});
I put it in $(window).load()
because it simply doesn't work in document.ready()
:
the latter fires up before the images are loaded and so before their dimensions are known.
(To be more precise, in fact it also works, but only because the images are already in browser's cache. If you empty the cache, it would fail on next following display).
Upvotes: 0
Reputation: 3145
This is the idea behind the (poorly supported) max-width
and max-height
attributes. These are supposedly supported in IE7, and they're supported in everything else modern.
On the image, you could set max-width
, max-height
, giving support for IE > 7 and everything else, and then pick whichever you really need the most between width
and height
using an IE6 conditional to set that. It won't look quite the same on IE6, but it's a simple solution. (IE6 usage is down around 10%, so this isn't that bad anymore.)
Or you could use the "IE7" library and just set max-width and max-height, at the expense of another odd Javascript library.
Upvotes: 1