HTML + Javascript: dynamically resizing an image?

I am trying to get some javascript to programmatically adjust the width of the html img tag to display images of various sizes.

I have a fixed img tag of 800 pixels to display an image, this is the maximum width.

If the image is wider, then 800 pixels, I want to display it with a width of 800 pixels,

If the image size is less than 800 pixels, I want to keep its width so as not to stretch it.

I use this html / javacript code to get a partial solution:

<html> <head> <script type="text/javascript"> <!-- function resize_image( id ) { var img = document.getElementById( id ); var normal_width = img.width; img.removeAttribute( "width" ); var real_width = img.width; if( real_width < normal_width ) img.width = real_width; else img.width = normal_width; } //--> </script> </head> <body> <img id="myimage" onload="resize_image(self.id);" src="IMAGE.JPG" width="800" /> </body> </html> 

The above code works in all browsers that I tested, except for Safari (images do not appear if you do not refresh the page).

I know that I can use the maximum CSS width, but this will not work on IE <7, which is an exponential stopper.

How can I make this work for all browsers? Thank you very much in advance.

+4
source share
4 answers

I have never seen a safari work, but you can try changing the onload event:

 onload="resize_image(self.id);return true" 

It is possible that without a return value, safari believes that this object should not be loaded.

+3
source

Use IE6 css + javascript hack:

  .dynamic_img { width: expression(document.body.clientWidth <= 800? "auto" : "800px"); max-width: 800px; //For normal browsers } 
+2
source

Without id:

 ... function resize_image( img ) { //var img = document.getElementById( id ); ... <img onload="resize_image(this);" src="IMAGE.JPG" width="800" /> 
+1
source

Have you tried monkey with img.style.width ? You can also try having 2 CSS classes for each of the two conditions and change them programmatically.

0
source

All Articles