Last active
January 4, 2016 08:11
-
-
Save zachmayberry/7243140 to your computer and use it in GitHub Desktop.
Parallax scroll event optimization for changing background images and not disrupting the fluid scroll
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
/* | |
Used in conjunction with Scott Robin's backstretch script: | |
https://github.com/srobbin/jquery-backstretch | |
*/ | |
(function($) { | |
var justExecuted = false; | |
$(window).on('scroll', function() { | |
// Slow down event execution with timeout set below | |
if ( justExecuted ) { | |
return; | |
} | |
// Cache all values and elements used below | |
var width, | |
backStretch, | |
isFixed, | |
$body = $('body'), | |
$menu = $('.menu'), | |
$backStretchEl = $('.backstretch img'), | |
$scrollPosition = $body.scrollTop(); | |
// console.log($scrollPosition); // for testing breakpoints | |
// Switch became increasingly efficient here | |
switch( true ) { | |
case ($scrollPosition < 150): | |
if ( backStretch == 1 ) return; | |
$backStretchEl.attr('src', 'images/bg1.jpg'); | |
backStretch = 1; | |
break; | |
case ($scrollPosition < 1000): | |
if ( backStretch == 2 ) return; | |
$backStretchEl.attr('src', 'images/bg2.jpg'); | |
backStretch = 2; | |
break; | |
case ($scrollPosition < 1700): | |
if ( backStretch == 3 ) return; | |
$backStretchEl.attr('src', 'images/bg3.jpg'); | |
backStretch = 3; | |
break; | |
case ($scrollPosition < 3000): | |
if ( backStretch == 4 ) return; | |
$backStretchEl.attr('src', 'images/bg4.jpg'); | |
backStretch = 4; | |
break; | |
case ($scrollPosition < 4300): | |
if ( backStretch == 5 ) return; | |
$backStretchEl.attr('src', 'images/bg5.jpg'); | |
backStretch = 5; | |
break; | |
} | |
// Reset timeout periodically (increase for better performance, but decreased accuracy) | |
justExecuted = true; | |
setTimeout(function() { | |
justExecuted = false; | |
}, 100); | |
}); | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment