// jquery.backgrounds.js // Search container for images and treat that 100% full image backgrounds // version 1.0 // by Joshua Gildart ;(function($, window, undefined) { $.backgrounds = function(element, options) { // default plugins options var defaults = { }; $container = $(element); var bg = this, images; bg.init = function() { // setup the container if($container.css('position') == 'static') { $container.css('position', 'relative'); } $container.css('overflow', 'hidden'); images = $container.find('img'); images.css({ position: 'absolute' }); // let the window load before we go crazy $(window).load(function() { $(window).resize(function() { adjustImages(); }); $(window).trigger('resize'); $container.mousedown(function(e){ e.preventDefault(); }); adjustImages(); }); } var adjustImages = function() { images.css({ top: 0, left: 0 }); images.each(function() { var image = $(this), imgW = image.width(), imgH = image.height(), viewportW = $container.width(), viewportH = $container.height(), diffW = viewportW / imgW, diffH = viewportH / imgH, centerWidth; if(diffW > 1 || diffW > diffH) { // the width needs adjusting image.width(viewportW); image.height('auto'); centerWidth = false; } else if(diffH > 1 || diffH > diffW) { // the height needs adjusting image.height(viewportH); image.width('auto'); centerWidth = true; } if(centerWidth) { // center by width - 0.9999 is to fix IE9's inability to be 1 image.css('left', -1 * Math.round((image.width() - viewportW) / 2)); } else { // center by height image.css('top', -1 * Math.round((image.height() - viewportH) / 2)); } }); } bg.init(); } $.fn.backgrounds = function(options) { return $(this).each(function() { if (undefined == $(this).data('backgrounds')) { var backgrounds = new $.backgrounds(this, options); $(this).data('backgrounds', backgrounds); } }); } })(jQuery, window);