开发者

How to detect if a click() is a mouse click or triggered by some code? [duplicate]

This question already has answers here: In jQuery, how can I tel开发者_如何学编程l between a programmatic and user click? (7 answers) Closed 6 years ago.

How to detect if a click() is a mouse click or triggered by some code?


Use the which property of the event object. It should be undefined for code-triggered events:

$("#someElem").click(function(e) {
    if(e.which) {
        //Actually clicked
    }
    else {
        //Triggered by code
    }
});

Here's a working example of the above.

Update based on comments

Pressing the Enter key when an input element has focus can trigger the click event. If you want to distinguish between code-triggered clicks and all other clicks (mouse or keyboard triggered) then the above method should work fine.


You should check e.originalEvent:

$("#someElem").click(function(e) {
    if(e.originalEvent === undefined) {
        //triggered 
    }
    else {
        //clicked by user
    }
});


Wait for some time and use event.isTrusted - its supported by IE9, Opera 12, and Firefox Nightly. Webkit will support it too, most probably.

Currently, there is no guaranteed way to know.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜