Auto Restrain/resize images with Javascript

106

This javascript script resizes all image on the page, it can be controlled by the variable i and the greater than clause in the for loop. i=0 means it starts from the first image, change i=3 it will start from the forth image. The greater than clause will resize x amount of images. right now it resizes 10 images. The first 100 seen decides if the image is under 100 pixels wide not to resize it to 100, the second is what to resize the image too.  comment any questions

<script language="javascript" type="text/javascript">
<!--
function resize_images()
{
for (i = 0; i < 10; i++)
{
while ( !document.images[i].complete )
{
break;
}
if ( document.images[i].width > 100 )
{
document.images[i].width = 100;
}
}
}
//-->
</script>

To implement the function on the page use this as your body tag

<body onLoad="resize_images()">



10 comments ↓

If you found this post useful click the share this button. Contribute below by adding a comment, no registration is required.


  • Michael says on 11.12.08 at 11:20 am comment #1

    Nice simple script. Only iussue I have is an IE 7 script error which states:

    Message: ‘document.images[...].complete’ is null or not an object

    Any suggestions?

  • ardeay says on 11.17.08 at 10:34 am comment #2

    Do you have a link to where you are using it?

  • Michael says on 11.18.08 at 9:56 am comment #3

    Thanks for the reply. I changed the amount of images to resize from 10 to 9 and it seemed to fix the issue. So Im thinking it may have been with the 2 digits. So instead of:

    for (i = 0; i < 10; i++)

    I used

    for (i = 0; i < 9; i++)

    and I didnt receive an IE7 error. Firefox works either way.

  • John says on 01.16.09 at 11:03 am comment #4

    Hi, great tutorial; I can’t seem to get it running under IE7 either. Firefox worked like a charm, any ideas?

  • Roberto says on 05.16.09 at 2:41 am comment #5

    great script – it worked fine, but if i want to change one particluar image – what can i do?

  • العاب says on 06.03.09 at 10:03 am comment #6

    Thank you,
    Look for the code, the time

  • sahibinden says on 08.20.09 at 2:22 pm comment #7

    Teşekkürler designcodeexecute.com sayenizde tasarımlarıma renk katıyorum:)

  • ardeay says on 08.28.09 at 10:20 pm comment #8

    @roberto bive the image an id the use getElementById

  • kuba says on 02.18.10 at 7:32 am comment #9

    @ardeay could give an example how to do it? I’m interested too to change the script so it could work with selected images on web page, not all of theme.
    Maybe the author could give a hand? :)

  • Bruce says on 05.19.10 at 9:42 am comment #10

    Nice simple script. Only iussue I have is an IE 7 script error which states:

    Message: ‘document.images[...].complete’ is null or not an object

    Any suggestions?

Leave a Comment