(function($) { $.fn.extend({ coverElement: function(options) { var settings = $.extend(true, { container: 'html' //Default is fit the viewport }, options); var $elements = this, $container = this.first().closest(settings.container); function applyCover() { $elements.each(function() { var $img = $(this); var windowheight = $container.height(), windowwidth = $container.width(), imageheight = $img.height(), imagewidth = $img.width(); var widthratio = windowwidth/imagewidth, heightratio = windowheight/imageheight; console.log(imagewidth, imageheight, $container); if(widthratio < heightratio) { //Too high/small $img.height(windowheight) //Fill height .width(imagewidth * heightratio) //Scale proportinately .css('left', ($img.width() - windowwidth) / -2) //Pull left by half of overflow .css('top', 0); //Reset from possible previous scaling } else if(widthratio > heightratio) { //Too wide/narrow $img.width(windowwidth) //Fill width .height(imageheight * widthratio) //Scale proportinately .css('top', ($img.height() - windowheight) / -2) //Pull up by half of overflow .css('left', 0); //Reset from possible previous scaling } else { //Fits exactly $img.width(windowwidth); $img.height(windowheight); } }); } applyCover(); $(window).resize(applyCover); //Could be throttled } }); })(jQuery);