Skip to content

Instantly share code, notes, and snippets.

@webbyworks
Created October 25, 2013 12:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save webbyworks/7153627 to your computer and use it in GitHub Desktop.
Save webbyworks/7153627 to your computer and use it in GitHub Desktop.
Simple parallax. Regardless of where the image is placed on the page this jQuery dependant Javascript will scroll from top to bottom of the background-image of the div containing the parallax image. Adopted from: http://net.tutsplus.com/tutorials/html-css-techniques/simple-parallax-scrolling-technique/
$(document).ready(function() {
var $window = $(window);
var wH = $window.height();
var docH = $(document).height();
$('.CLASS-OF-PARALLAX-IMAGE-HERE').each(function(){ // edit the class name of the div containing the parallax image.
var $bgobj = $(this);
$(window).scroll(function() {
var coords, yCoord;
var bgoff = $bgobj.offset().top;
var bgH = $bgobj.height();
var ws = $window.scrollTop();
if ( bgoff > ws + wH ) {
yCoord = 0;
} else if ( ws > bgoff + bgH ) {
yCoord = 100;
} else {
if ( wH + ws > bgoff && docH - bgoff - bgH < wH ) {
yCoord = (ws + wH - bgoff) / (docH - bgoff);
} else {
yCoord = ws / (bgoff + bgH);
}
yCoord *= 100;
}
coords = '50% '+ yCoord + '%';
$bgobj.css({ backgroundPosition: coords });
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment