Skip to content

Instantly share code, notes, and snippets.

@greypants
Created August 20, 2012 22:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save greypants/3408912 to your computer and use it in GitHub Desktop.
Save greypants/3408912 to your computer and use it in GitHub Desktop.
JS: Scroll Event Handling
/*
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