callback callback - 3 months ago 7
Javascript Question

How to handle window scroll efficiently

I have the following code that is calling some function when the screen is scrolled above a certain offset.

var $window = $(window);
var doFunct = function () {
if ($window.scrollTop() > 200) {
console.log('Above 200');
} else {
console.log('below 200');
}
}
$window.scroll(doFunct);


What I want to achieve is that the function console logs only whenever the
scrollTop
changes between being above 200 and below it. Not every single time I scroll as it is the case now!.

Answer

You could set a variable to indicate the threshold has been crossed. Something like:

var $window = $(window);
var threshold = false;
var doFunct = function () {
    if ($window.scrollTop() > 200) {
       if(!theshold){
          console.log('Above 200');
          theshold = true;
       }
    } else {
       if(theshold){
          console.log('below 200');
          theshold = false;
       }
    }
}
$window.scroll(doFunct);