Skip to content

Instantly share code, notes, and snippets.

@joshmvandercom
Created June 25, 2012 20:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save joshmvandercom/2990885 to your computer and use it in GitHub Desktop.
Save joshmvandercom/2990885 to your computer and use it in GitHub Desktop.
autoresizer
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