Created
June 25, 2012 20:00
-
-
Save joshmvandercom/2990885 to your computer and use it in GitHub Desktop.
autoresizer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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>'); | |
} | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment