Skip to content

Instantly share code, notes, and snippets.

@jofralogo
Last active August 29, 2015 13:56
Show Gist options
  • Save jofralogo/9185468 to your computer and use it in GitHub Desktop.
Save jofralogo/9185468 to your computer and use it in GitHub Desktop.
Parallax backgrounds for non-touch devices (using jQuery & Modernizr)
/*
HTML SYNTAX:
<div id="example" data-parallax-bg="false" data-parallax-bg-speed="1.5">
CONTENT
</div>
IMPORTANT:
Don't forget tu place the background-image on your css file:
#example{
background: url(imgs/example.jpg) no-repeat;
background-size: cover;
}
NOTES:
This script follows mobile-first methodology. By default the effect is disabled and only if Modernizr detects that the visitor is using a non-touch device, the effect is enabled.
CREDITS:
This script is based on http://code.tutsplus.com/tutorials/simple-parallax-scrolling-technique--net-27641 and tweaked by myself (@jofralogo)
*/
$(document).ready(function(){
// OPTIONAL: Using Modernizr to detect non-touch devices and enable the effect on them.
$('.no-touch *[data-parallax-bg="false"]').attr('data-parallax-bg', 'true').css('background-attachment', 'fixed !important');
// Magic!
var $window = $(window);
$('[data-parallax-bg="true"]').each(function(){
var $bgobj = $(this); // assigning the object
$(window).scroll(function() {
var yPos = -( ($window.scrollTop() - $bgobj.offset().top) / $bgobj.data('parallax-speed'));
// Put together our final background position
var coords = '50% '+ yPos + 'px';
// Move the background
$bgobj.css({ backgroundPosition: coords });
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment