Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to distinguish between mouse click and .click() in javascript/jquery? [duplicate]

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

like image 816
omega Avatar asked Oct 15 '25 07:10

omega


1 Answers

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/

like image 67
Joe Avatar answered Oct 17 '25 19:10

Joe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!