Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect jquery event trigger by user or call by code

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.

like image 378
James Avatar asked Jun 15 '12 10:06

James


People also ask

How do you check event is triggered or not in jQuery?

$('button'). click(function(event, wasTriggered) { if (wasTriggered) { alert('triggered in code'); } else { alert('triggered by mouse'); } }); $('button').

How do you know if an event is triggered?

To check if event is triggered by a human with JavaScript, we can use the isTrusted property. to check if the event is triggered by a human in our event handler callback. e is the event object and it had the isTrusted property. If isTrusted is true , then the event is triggered by a human.

What is trigger method in jQuery?

jQuery trigger() Method The trigger() method triggers the specified event and the default behavior of an event (like form submission) for the selected elements. This method is similar to the triggerHandler() method, except that triggerHandler() does not trigger the default behavior of the event.


2 Answers

$('#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

like image 180
thecodeparadox Avatar answered Sep 16 '22 11:09

thecodeparadox


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

like image 21
Ramon Avatar answered Sep 17 '22 11:09

Ramon