3

In javascript/jquery, I have a button that have a click event defined like:

$("#target").click(function() {
    var mouse_click = ________________;
    // do stuff
    if (mouse_click) {
        // do stuff  
    }
    // do stuff
});

and I also have code to do

$('#target').click();

How can I get the variable mouse_click to be true, if the user manually clicked the tag using the mouse, and the variable to be false when I click the tag using the .click() function?

Thanks

omega
  • 40,311
  • 81
  • 251
  • 474

1 Answers1

6

You could use this:

$("#target").click(function(e) {
    var mouse_click = !(e.originalEvent === undefined);
    // do stuff
    if (mouse_click) {
        // do stuff  
    }
    // do stuff
});

or you could check e.isTrigger which is set whenever an event is triggered within jQuery. You'd just need to change the second line to:

var mouse_click = !e.isTrigger;

Both will work but you might prefer the second option as it's a little more concise.

Here it is working: http://jsfiddle.net/2U3Us/4/

Joe
  • 15,205
  • 8
  • 49
  • 56
  • 1
    Is there a reason to use the `? :` operator here? I know JS occasionally does weird conversions, but I'd lean toward the simpler `!(e.originalEvent === undefined)` and `!e.isTrigger`, myself. – Xavier Holt Jun 02 '13 at 17:57
  • @XavierHolt - good point, it must have slipped my mind. I've just updated my answer and fiddle. – Joe Jun 02 '13 at 18:18