Created
June 7, 2012 20:37
-
-
Save yorch/2891402 to your computer and use it in GitHub Desktop.
Variable Size Background (jQuery)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function() { | |
// Background image variable size (keeping aspect ratio fixed) | |
// Based on http://jonathanstark.com/blog/2011/01/03/variable-size-background-image/ | |
// By Jorge Barnaby (jorge {dot} barnaby {at} gmail) - Jun 2012 | |
// Background image | |
var imgPath = 'assets/background.jpg'; // Path of the image to be used as background | |
var origW = 1920; // Original width of the image | |
var origH = 1080; // Original height of the image | |
var ratio = origW / origH; | |
// Image jQuery object | |
var bgImg = $('<img>').attr('src', imgPath).height(origH).width(origW).css({position: 'absolute', left: '0px', top: '0px', zIndex: '-1'}); | |
// Background wrapper jQuery object | |
var bg = $('<div></div>').height(origH).width(origW).css({position: 'absolute', left: '0px', top: '0px', zIndex: '-1'}); | |
// Append elements | |
bg.append(bgImg); | |
$('body').append(bg); | |
// Set the image size based on window size | |
setBackgroundImageSize(); | |
// Prevent page scrolling on touch devices | |
$('body').bind('touchmove', function(e) { | |
e.preventDefault(); | |
}); | |
//Bind resize function to events | |
$(window) | |
.bind('resize', function() { | |
setBackgroundImageSize(); | |
}) | |
.bind('orientationchange', function () { | |
setBackgroundImageSize(); | |
}); | |
function setBackgroundImageSize() { | |
var w = $(window).width(); | |
//var h = $(window).height(); | |
var h = Math.round(w / ratio); | |
$(bg).height(h).width(w); | |
$(bgImg).height(h).width(w); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment