How to detect if a click() is a mouse click or triggered by some code? [duplicate]
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.
精彩评论