Change the size of the images dynamically using javascript

From Code Trash
Jump to: navigation, search

Is this explanation really important? not at all. then???. I have never used this onload option and was surprised that it works for all browsers. I got exited and hence this.

Assume that you want to display images with in a square of width 150px. You have a list of images which are generated using php inside a loop. So probably you are going to display 10 to 15 images. But some images width could be than the parent square's width that is 150px. This will not look good so you want to set the width of the image attribute here to less than 150 if it is more than that.

There is one option with php. you could use getimagesize for each image and if it is greater than 150 you are going to set the width of the img tag to be 150 or if the image width is less than 150 then you are going to leave it as it is. But this takes more time to load the image SPECIALLY IF YOU ARE DISPLAYING ANOTHER SITES IMAGE.

So here comes this silly javascript work with which you can set the width. Also you can consider not to display the image before it is loaded completely. for that you can by default set the visibility of the image to hidden use the following script to set the width and show the image only after it has loaded completely and untill that you can show a processing image to show the user that the image is loading.


<script type="text/javascript">
var simg = new Image();
simg.src = '';
simg.onload = function()
     if(simg.width>150) = '150px'


you can give it inline like this

<img src="" onload="if(this.width>150)'150px';" />

Note: Using php to find the image size from other sites takes little more time to load all the images. So is this tip. And this is for my documentation.