Forum Moderators: open

Message Too Old, No Replies

Image Max height and width by %

max, height, width, image

         

mike7

11:31 am on May 28, 2007 (gmt 0)

10+ Year Member



Hi all!

I got a question,

How can i fix the image MAX. Height and Width?

e.g.
my image size= 600X900
the browers size = 800X600
then the image will auto resize to the height less the 600 and the width will also resize by ratio...

how can i set the image max height and width to 90% of the browser size?

Thanks for all u help! ;-)

Dabrowski

5:46 pm on May 29, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



ok, you need to id your <img> so we can find it. You'll need this in your html:

<img id='nottoobig' ...>

Now, a little code. I'm making the following assumtions in this code, first that you want to check the height and the width, second that it won't scale an image up if it's too small.


function checkImageSize() {
var img = document.getElementById( "nottoobig");
var bdy = document.body;
var a = img.width / img.height;

if( img.width > bdy.clientWidth *0.9) {
img.width = Math.floor( body.clientWidth *0.9);
img.height = img.width *a;
}

if( img.height > bdy.clientHeight *0.9) {
img.height = Math.floor( body.clientWidth *0.9);
img.width = img.height *a;
}
}

It's untested but should work. It'll do a double pass - it'll set the width, and then still check the height afterwards, that should work with the example below.

You'll also have to add an onLoad handler to call it.