Category Archives: jQuery

11
Dec

Resize Images Using jQuery

Today I needed a script to resize images on the fly dynamically. I did not want to lose the ratio of the image, so found a little jQuery script on how to do it. :)

var max_size = 200;
$("img").each(function(i) {
  if ($(this).height() > $(this).width()) {
    var h = max_size;
    var w = Math.ceil($(this).width() / $(this).height() * max_size);
  } else {
    var w = max_size;
    var h = Math.ceil($(this).height() / $(this).width() * max_size);
  }
  $(this).css({ height: h, width: w });
});

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.

Credit: Adeel Ejaz
Source: http://adeelejaz.com/blog/resize-images-on-fly-using-jquery/




© Copyright 2010-2013 KaBaDaBrA. All rights reserved. Created by Dream-Theme — premium wordpress themes. Proudly powered by WordPress.

Switch to our mobile site