Reputation: 490173
Consider this jQuery code:
$('button#my').click(function(event) {
alert('hello');
});
$('button#my').click();
Obviously, this will bring up an alert window.
However, can I tell, with jQuery only, if that event handler was triggered with code or if the user clicked it (without ugly flag checking, e.g. var userClicked = true
).
I thought there would be a property of event
, but I couldn't figure it out.
Is this possible?
Upvotes: 3
Views: 538
Reputation: 322492
Late answer. Nick's answer would work, but you can do it in a little more explicit manner.
You can define your .click()
with additional parameters, and pass those parameters by using .trigger('click')
instead of .click()
.
Example: http://jsfiddle.net/patrick_dw/jWFAn/
// Passed via .trigger() ----------------v
$('button#my').click(function(event, wasManual) {
if( wasManual ) {
alert('triggered in code');
} else {
alert('triggered by mouse');
}
});
// Array of additional args------v
$('button#my').trigger( 'click', [true] );
This way it is using an explicit feature of jQuery in its supported manner.
Upvotes: 1
Reputation: 90742
I just tried it out and there are many differences between them; have Firebug and try $("button#my").click(console.log)
and you'll see the event logged when you click or click()
. One is event.currentTarget
which is the element when clicked, or document
when click()
ed (may be subject to change based on the scope it's called in, experiment). There are all sorts of other differences too - (offset|client|layer)[XY]
are all set for click but not click()
, and more.
(Edit: as Nick says, event.which
is another; it's 1 for click and not defined for click()
.)
Upvotes: 1
Reputation: 630379
You can check event.which
, it'll be undefined
for the .click()
(or other trigger) calls...for example:
$('button#my').click(function(event) {
if(event.which) {
alert("User click");
} else {
alert("triggered click");
}
});
Upvotes: 7