Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In jQuery, how can I tell between a programmatic and user click?

Tags:

jquery

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?

like image 568
Kevin Owocki Avatar asked Jul 13 '11 06:07

Kevin Owocki


People also ask

What is the difference between on click and click in jQuery?

on() differs from . click() in that it has the ability to create delegated event handlers by passing a selector parameter, whereas . click() does not. When .

What is click in jQuery?

jQuery click() MethodThe click event occurs when an element is clicked. The click() method triggers the click event, or attaches a function to run when a click event occurs.

How do you trigger a click in JavaScript?

Trigger Click Event in JavaScript Using click() An element receives the click event when pressed, and a key is released on the pointing device (eg, the left mouse button) while the pointer is within the element. click() is triggered after the down and up mouse events are triggered in that order.


1 Answers

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/

like image 90
mu is too short Avatar answered Oct 05 '22 23:10

mu is too short