I successfully resolved the code mentioned in the original post.
Check out the Github repository for the rewritten version of the initial plugin.
$('img.test').photoResize({
upscaleImageWidth: false,
upscaleImageHeight: false
});
This solution addresses the issue by also considering the viewport height, a factor not accounted for in a CSS-only approach. It represents an enhanced iteration of the concept initially presented by the OP.
Here is the complete code for the plugin:
(function ($) {
$.fn.photoResize = function (options) {
var element = $(this),
defaults = {
bottomSpacing: 10,
rightSpacing: 20,
unscaledHeight: $(element).height(),
unscaledWidth: $(element).width(),
upscaleImageWidth: true,
upscaleImageHeight: true
};
options = $.extend(defaults, options);
$(element).load(function () {
changeDimensions();
});
changeDimensions();
$(window).bind('resize', function () {
changeDimensions();
});
function changeDimensions() {
if (options.unscaledHeight == 0) {
options.unscaledHeight = $(element).height();
options.unscaledWidth = $(element).width();
}
if (options.unscaledHeight == 0) return;
var maxDisplayHeight = $(window).height() - $(element).offset().top - options.bottomSpacing;
var maxDisplayWidth = $(window).width() - $(element).offset().left - options.rightSpacing;
var desiredHeight = maxDisplayHeight < options.unscaledHeight || options.upscaleImageHeight ? maxDisplayHeight : options.unscaledHeight;
var desiredWidth = maxDisplayWidth < options.unscaledWidth || options.upscaleImageWidth ? maxDisplayWidth : options.unscaledWidth;
var currHeight = $(element).height();
var currWidth = $(element).width();
if (currHeight != desiredHeight || currWidth != desiredWidth) {
if (desiredHeight / options.unscaledHeight <= desiredWidth / options.unscaledWidth) {
$(element).height(desiredHeight);
$(element).width(options.unscaledWidth * desiredHeight / options.unscaledHeight);
} else {
$(element).height(options.unscaledHeight * desiredWidth / options.unscaledWidth);
$(element).width(desiredWidth);
}
}
}
};
}(jQuery));