Skip to content

Instantly share code, notes, and snippets.

@johndwells
Created March 25, 2012 14:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johndwells/2195281 to your computer and use it in GitHub Desktop.
Save johndwells/2195281 to your computer and use it in GitHub Desktop.
Example of fullscreen background images.
app.backstretchImgs = function() {
$.each($('img.backstretch'), function() {
var $img = $(this);
// bind to resize
$(window).bind('resize', function(event) {
// remember to place into DOM first if you need access to width & height
// access width & height with this.width and this.height
var imgRatio = $img.width / $img.height,
windowWidth = $(window).width(),
windowHeight = $(window).height(),
windowRatio = windowWidth / windowHeight;
if ( imgRatio > 1 && windowRatio <= imgRatio)
{
var bgHeight = windowHeight,
bgWidth = (imgRatio > 1 && windowRatio <= imgRatio) ? (windowHeight / $img.height) * $img.width : bgHeight * imgRatio,
bgCSS = {
'top' : 0,
'left' : ((windowWidth - bgWidth) / 2) + 'px'
};
} else {
var bgWidth = windowWidth,
bgHeight = (imgRatio > 1 && windowRatio >= imgRatio ) ? (bgWidth / $img.width) * $img.height : bgWidth / imgRatio,
bgCSS = {
'left' : 0,
'top' : ((windowHeight - bgHeight) / 2) + 'px'
};
}
$img
.width(bgWidth)
.height(bgHeight)
.css(bgCSS);
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment