Resize images using jQuery

UPDATE: I have created a plugin that dynamically resizes the images using jQuery. It basically does the same job but is really easy to use and is optimized better (minified).

Recently I needed a script to resize images on the page. I did not want to lose the actual resolution but just wanted to create thumbnails on the go.

I spent some time searching but could not find anything suitable. The options I found were just too much while I needed something simple. At the end, I ended up writing some own code (I’m a coder after all :P).

The script resizes the images without distorting the proportions. First of all, a variable is declared called max_size that is set to the maximum height or width that the picture needs to be resized to. Then using jQuery we match all img elements and using the each function, we go through each one of them resizing them as necessary. The if statement checks which side of the image needs to be kept to the maximum and the other one is calculated proportionally.

In the final line, the new height and width values are assigned using CSS. Neat eh 😉

Flattr this!

  • Nice job.
    Clearly you can generalize the concept by applying different types of manipulations, such as:
    1. rounded corners
    2. alpha effect
    3. wrap with a link
    4. set ALT / Title

    • Don’t understand what you mean. I’m guessing you can use CSS for rounded corners, etc.

    • Trixit

       you are so lazy…

  • geedmo

    Excellent code! thanks for the scripts.. it was really useful for me and works really fine !

    I made a simplified version if you’re interested… is the same but I just want to share with you.. 🙂

     containerwd and  containerhg are the size of the, div, span.. who determines the size where the image is wrapped 

    $(“img”).each(function(i) {
    imghg = ((naturalimgwd/ naturalimghg < containerwd / containerhg) ? 
                 containerhg : 
                 Math.ceil(containerwd/naturalimgwd * naturalimghg)); 

    imgwd = ((f.o.naturalimgwd/f.o.naturalimghg < containerwd/containerhg) ? 
                 Math.ceil(containerhg/naturalimghg * naturalimgwd) :

    $(this).css({ height:
    , width:

  • This is awesome! Works like a charm. Thanks a lot

  • thanks for the scripts..