Created
August 20, 2012 22:58
-
-
Save greypants/3408912 to your computer and use it in GitHub Desktop.
JS: Scroll Event Handling
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
/* | |
Check scroll position on a timer | |
Instead it's much better to use some form of a timer to check every X milliseconds OR to attach a scroll event and only run your code after a delay (or even after a given number of executions - and then a delay). | |
http://ejohn.org/blog/learning-from-twitter/ | |
*/ | |
var didScroll = false; | |
var handleScroll = function() { | |
if ( didScroll ) { | |
didScroll = false; | |
// Check your page position and do stuff | |
} | |
}; | |
$(window).scroll(function() { | |
didScroll = true; | |
}); | |
setInterval(handleScroll, 250); | |
/* | |
ALTERNATE FUNCTIONALITY: Check only after a completed scroll. | |
One technique you can use is to set a timer on the scroll event and only do the main work when the scroll position hasn't changed for a short period of time. | |
http://stackoverflow.com/questions/7392058/more-efficient-way-to-handle-window-scroll-functions-in-jquery | |
*/ | |
var scrollTimer = null; | |
var handleScroll = function() { | |
scrollTimer = null; | |
}; | |
$(window).scroll(function () { | |
if (scrollTimer) { | |
clearTimeout(scrollTimer); // clear any previous pending timer | |
} | |
scrollTimer = setTimeout(handleScroll, 500); // set new timer | |
}; | |
/* | |
EXAMPLE: | |
======== | |
*/ | |
var didScroll = false; | |
var $window = $(window); | |
var $element = $('.element'); | |
var browserHeight = $window.height(); | |
var height = $element.height(); | |
var offsetTop = $element.offset().top; | |
var minScroll = offsetTop - browserHeight; | |
var maxScroll = offsetTop + height; | |
var scrollTop = 0; | |
var handleScroll = function() { | |
if(didScroll) { | |
didScroll = false; | |
scrollTop = $window.scrollTop(); | |
if(scrollTop > minScroll && scrollTop < maxScroll) { | |
console.log('ON SCREEN!') | |
} else { | |
console.log('off screen...') | |
} | |
} | |
}; | |
$(window).scroll(function() { | |
didScroll = true; | |
}); | |
setInterval(handleScroll, 250); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment