10

I have some window.onscroll event

$(window).scroll(function(e){
    //My Stuff
});

but in my code I call animate scroll to some where

$('html, body').stop().animate({
   scrollTop:555
}, 1000);

so how I detect the page was scroll by user or call by my code. My current solution is put a flag before call animate in my code then clear it but it's not clever solution. I've also read about detect e.which or e.originalEvent but it's not work. I think you expert have a good solution here.

James
  • 13,571
  • 6
  • 61
  • 83
  • Wait, why the flag solution isn't good enough? What's not clever with it? – gdoron Jun 15 '12 at 10:54
  • @gdoron: Flag once set to true will always be true because he can't detect whether user scrolled himself and there by set that flag to false again as far as I understand from the question. – Sarfraz Jun 15 '12 at 10:57
  • I have call the animate in multiple place, so update all of them will not smart enough. But then what happen when user interrupt the animate by scroll the page? The flag cannot help – James Jun 15 '12 at 10:58
  • @Sarfraz flag can be set to false when the animate complete (in jquery) – James Jun 15 '12 at 10:59

2 Answers2

19
$('#scroller').scroll(function(e) {
    if (e.originalEvent) {
        // scroll happen manual scroll
        console.log('scroll happen manual scroll');
    } else {
        // scroll happen by call
        console.log('scroll happen by call');
    }
});

$('#scroller').scroll(); // just a initial call

When you scroll by call the e.originalEvent will undefined but when scroll manually it will give scroll object.

DEMO

thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
  • 1
    Hey, interesting. If I use `$('#scroller').scroll();` then it can detect happen by call, but if I use `$('#scroller').animate({scrollTop: 200}, 1000);` it said manual scroll. Is that a lie? – James Jun 15 '12 at 11:40
  • 5
    Does not work for me: e.originalEvent is always there and identical in both cases. – steph643 Oct 26 '14 at 10:04
  • Using jQuery 1.12.3, e.originalEvent is always there. I mean for manual trigger or not (not tested for animation). Though, to be precise, the scroll event is called because after an animation (on callback) I set back the original scroll value. – Master DJon Oct 27 '16 at 20:13
  • Can this be altered, so that it works without jQuery too? – PjotrC Feb 02 '21 at 22:26
3

ive reasked this question and got 2 helpful answers.
i'll link the question here for others who'll find this thread.

Detect if a scroll event is triggered manually in jQuery

Community
  • 1
  • 1
Ramon
  • 424
  • 2
  • 9
  • 24