Reputation: 1381
I must check which is fired the click event, click with mouse or .click() function. Is it possible?
Upvotes: 0
Views: 231
Reputation: 26143
Yes, you can do that like this...
$('button').on("click", function(e){
if (e.originalEvent !== undefined) {
// the button was actually clicked
} else {
// the button was triggered by code
}
});
Upvotes: 1
Reputation: 1074258
You can tell by looking at the pageX
or pageY
property of the event object, which will be undefined
if $("some selector").click();
was used, but a number if an actual mouse click occurred. For example:
(function($) {
$("#target").click(function(e) {
if (typeof e.pageX === "undefined") {
display("Fired programatically");
}
else {
display("Fired by real click");
}
});
setTimeout(function() {
$("#target").click();
}, 500);
function display(msg) {
$("<p>").html(String(msg)).appendTo(document.body);
}
})(jQuery);
Of course, if someone gets really clever and builds a full click event including fake pageX
and pageY
information, that won't work, but jQuery's default handling of $("some selector").click();
doesn't do that.
Upvotes: 1