Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if a click() is a mouse click or triggered by some code? [duplicate]

How to detect if a click() is a mouse click or triggered by some code?

like image 482
clarkk Avatar asked Oct 03 '11 12:10

clarkk


People also ask

How do you check if the element is clicked?

To check if an element was clicked, add a click event listener to the element, e.g. button. addEventListener('click', function handleClick() {}) . The click event is dispatched every time the element is clicked.

How do you trigger a click element?

The HTMLElement. click() method simulates a mouse click on an element. When click() is used with supported elements (such as an <input> ), it fires the element's click event. This event then bubbles up to elements higher in the document tree (or event chain) and fires their click events.

How do you find a click in HTML?

You can detect clicks inside the page with a simple click event handler: document. onclick= function(event) { // Compensate for IE<9's non-standard event model // if (event===undefined) event= window.


1 Answers

Use the which property of the event object. It should be undefined for code-triggered events:

$("#someElem").click(function(e) {
    if(e.which) {
        //Actually clicked
    }
    else {
        //Triggered by code
    }
});

Here's a working example of the above.

Update based on comments

Pressing the Enter key when an input element has focus can trigger the click event. If you want to distinguish between code-triggered clicks and all other clicks (mouse or keyboard triggered) then the above method should work fine.

like image 90
James Allardice Avatar answered Sep 18 '22 17:09

James Allardice