pbojinov
2/20/2013 - 7:16 PM

autoresize.js

jQuery.fn.autoresize = function (options) {
  options = options || {}
  return this.each(function () {
    //  Init Sizes
    var parent = $(this).parent();
    var imageWidth = $(this).width();
    var imageHeight = $(this).height();
    var parentWidth = parent.width();
    var parentHeight = parent.height();
    var ratio, newSide;

    if (imageWidth > imageHeight) {
      if (imageHeight > parentHeight) {
        ratio = parentHeight / imageHeight;
      } else {
        ratio = imageHeight / parentHeight;
      }
      newSide = ratio * imageWidth;
      $(this).height(parentHeight);
      if (newSide > parentWidth) {
        $(this).css({
          'margin-left': parseInt((newSide - parentWidth)) * - 1
        });
      } else {
        $(this).css({
          'margin-left': parseInt((parentWidth - newSide)) * - 1
        });
      }
    } else if (imageWidth < imageHeight) {
      if (imageWidth > parentWidth) {
        ratio = parentWidth / imageWidth;
      } else {
        ratio = imageWidth / parentWidth;
      }
      newSide = ratio * imageHeight;
      $(this).width(parentWidth);
      if (newSide > parentHeight) {
        $(this).css({
          'margin-top': parseInt((newSide - parentHeight)) * - 1
        });
      } else {
        $(this).css({
          'margin-top': parseInt((parentHeight - newSide)) * - 1
        });
      }
    } else {
      $(this).height(parentWidth);
    }
    if (options.corners) {
      if (parent.hasClass(options.corners)) {
        parent.append('<div class="tr"></div><div class="tl"></div><div class="br"></div><div class="bl"></div>');
      }
    }
  })
}