Skip to content Skip to sidebar Skip to footer

JQuery Image resize Example

Reading Time: < 1 minute

How to dynamically image re-size after loaded images, by using JQuery.This script resizing images without distorting the proportions.jQuery match all img elements and using the each function, we go through each one of them resizing them as necessary.

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 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.