Skip to content

Instantly share code, notes, and snippets.

@quis
Created August 5, 2010 11:11
Show Gist options
  • Save quis/509577 to your computer and use it in GitHub Desktop.
Save quis/509577 to your computer and use it in GitHub Desktop.
// =============================================
//
// SCALE ELEMENTS TO FIT A FIXED CONTAINER SIZE
// ---------------------------------------------
//
// By Chris Hill-Scott 2009-10
//
// Code is public domain, reuse as desired
//
// Requires jQuery
//
// ---------------------------------------------
//
// TODO: Prevent re-looking up $(window)
//
// ---------------------------------------------
//
// USAGE: $("img").imageScale();
//
// =============================================
// Use self-executing anonymous function to create namespace
var qImageScale = (function() {
return {
// Object to hold our cache of jQuery objects and option objects
selectors: {},
// Wrapper for the image scaling function which scales
// cached object collections, rather than do a re-lookup,
// useful when the container resizes, for example
cached: function() {
$.each(
qImageScale.selectors,
function() {
this.$collection.imageScale(this.options);
}
)
},
// Apply image scaling to a jQuery collection
live: function(options) {
var defaults = {
scale: 0.9, // controls the ammount of matte around the image, "1" will completely fill the screen
attr: {
x: "data-width",
y: "data-height"
},
container: $(window),
speed: 100,
updateCache: true
},
options = $.extend({}, defaults, options),
max = {
x: parseInt(options.container.width() * options.scale), // parseInt() makes things look better in FF
y: parseInt(options.container.height() * options.scale)
},
$self = $(this);
// Only do costly re-selection when we need to (and cache objects when we don't)
if (options.updateCache) {
options.updateCache = false;
qImageScale.selectors[$self.selector] = {
$collection: $self,
options: options
};
}
// Behave nicely, return a jQuery object
return this.each(
function() {
var $img = $(this),
nat = {
x: $img.attr(options.attr.x),
y: $img.attr(options.attr.y)
},
newHeight = max.x/(nat.x/nat.y),
dimensions;
// Determine if image needs resizing in some way
if ((nat.x > max.x) || (nat.y > max.y)) {
dimensions = {
"width": (newHeight > max.y) ? "auto" : max.x, // This switch determines if we're resizing
"height": (newHeight > max.y) ? max.y : "auto" // based on excess height or width
};
} else { // Image is naturaly smaller than viewport
dimensions = {
"width": "auto", // Give size control back to the browser
"height": "auto"
};
}
$img.css(dimensions);
}
);
}
};
}());
// Hook our function into jQuery
jQuery.fn.imageScale = qImageScale.live;
// Hook our function into the window resize event, avoiding conflicts
jQuery(document).ready(function($){
$(window).resize(qImageScale.cached);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment