Javascript – Distinguishing between the user scrolling and programmatically scrolling using Javascript

javascriptjquery

I'm creating a scrolling effect using JQuery and I'm wondering if it's possible to distinguish between the user scrolling vs. programmatically scrolling.

I have something like this:

$('#element').on('scroll',function(e){
    $('#element').stop(true); // stop previous scrolling animation
    $('#element').animate({ // start new scrolling animation (maybe different speed, different direction, etc)
        scrollTop:...
    });
});

However, this event is triggered during every step of the animation. How can I tell if this event was triggered by the user or by the animation?

Best Answer

Use a variable to determine when you are scrolling programmatically

Example:

var programScrolling = false;

$('#element').on('scroll',function(e){
    if (programScrolling) {
        return;
    }

    $('#element').stop(true); // stop scrolling animation

    programScrolling = true;

    $('#element').animate({
        scrollTop:...
    });

    programScrolling = false;
});

Not sure if that is exactly what you want, but the concept should work.