In jQuery, how can I tell between a programmatic and user click?
Say I have a click handler defined:
$("#foo").click(function(e){
});
How can I, within the function handler, tell whether the event was fired programmatically, or by the user?
Solution 1:
You could have a look at the event object e
. If the event was triggered by a real click, you'll have things like clientX
, clientY
, pageX
, pageY
, etc. inside e
and they will be numbers; these numbers are related to the mouse position when the click is triggered but they will probably be present even if the click was initiated through the keyboard. If the event was triggered by $x.click()
then you won't have the usual position values in e
. You could also look at the originalEvent
property, that shouldn't be there if the event came from $x.click()
.
Maybe something like this:
$("#foo").click(function(e){
if(e.hasOwnProperty('originalEvent'))
// Probably a real click.
else
// Probably a fake click.
});
And here's a little sandbox to play with: http://jsfiddle.net/UtzND/
Solution 2:
You can use an extra parameter as stated in the jQuery trigger manual:
$("#foo").click(function(e, from){
if (from == null)
from = 'User';
// rest of your code
});
$('#foo').trigger('click', ['Trigger']);