How to detect if a click() is a mouse click or triggered by some code?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With