Skip to content

Instantly share code, notes, and snippets.

@andergmartins
Created October 17, 2012 03:29
Show Gist options
  • Save andergmartins/3903548 to your computer and use it in GitHub Desktop.
Save andergmartins/3903548 to your computer and use it in GitHub Desktop.
Fullscreen background image responsive
/**
* Fullscreen background image responsive
* @author Anderson G. Martins <[email protected]>
*/
(function ($) {
// Use image reload to fix empty dimensions
$.fn.imageSize = function(fn)
{
this.each(function() {
var img = new Image();
img.onload = function() {
fn(img.width, img.height);
};
img.src = $(this).attr("src");
});
};
$.fn.fullscreenBackground = function () {
var $window = $(window);
this.each(function() {
var $background = $(this);
$(this).imageSize(function(width, height) {
var imgAspectRatio = width / height;
$window.resize(function() {
var windowHeight = $window.height(),
windowWidth = $window.width(),
windowAspectRatio = windowWidth / windowHeight,
calcWidth = 0,
calcHeight = 0;
if (windowAspectRatio < imgAspectRatio)
{
calcWidth = windowHeight * imgAspectRatio;
calcHeight = windowHeight;
}
else
{
calcWidth = windowWidth;
calcHeight = windowWidth / imgAspectRatio;
}
calcWidth = calcWidth;
calcHeight = calcHeight;
$background.css('height', calcHeight);
$background.css('width', calcWidth);
$background.css('max-height', calcHeight);
$background.css('max-width', calcWidth);
$background.css('min-height', calcHeight);
$background.css('min-width', calcWidth);
}).trigger('resize');
});
});
};
// Calling fullscreenBackground
$('div#background img').load(function() {
$(this).fullscreenBackground();
});
})(jQuery)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment