Click source in JavaScript and jQuery, human or automated?

拥有回忆 提交于 2019-11-28 14:03:57

Try this:

$('#targetElement').click(function(event, generated) {
    if (generated) {
        // Event was generated by code, not a user click.
    } else {
        // Event was generated by a user click.
    }
});

Then, to make this work, you have to trigger them like this:

$('#targetElement').trigger('click', [true]);

See this jsfiddle.

Check out event.which, it'll be undefined if triggered with code.

$(document).click(function(event) {
    if (event.which) {
       // Triggered by the event.
    } else {
       // Triggered with code.
    }
});

jsFiddle.

Here's one way I have found (tested in Chrome)

$('#foo').click(function(e) {
    if (e.originalEvent)
        alert('Has e (manual click)');
    else
        alert('No e (triggered)');
});

See here for testing: http://jsfiddle.net/ZPD8w/2/

In your immediate event handler, provide an e parameter. If the click is automated (via code), this e would be undefined (no need to check e.target as @alex has said):

$('#targetElement').click(function(e){
   if(e)
   {
      // Click is triggered by a human action
   }
   else
   {
     // Click is triggered via code
   }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!