I'm only adding a click
event handler on my <button>
.
document.getElementsByTagName("button")[0].addEventListener("click", event => {
event.preventDefault();
console.log("Click:", event);
});
<button>Press <kbd>Enter</kbd> on me</button>
(Demo link)
Nevertheless, when I tab to the button in Firefox, then press Enter, I see the click
event being fired. However, I cannot see this behaviour documented anywhere. Is this standard behaviour, and can I count on it working in all browsers?
Solution 1function (event) { if (event. which == 13 || event. keyCode == 13) { //code to execute here return false; } return true; }); Implement it according to your need.
Conclusion. To disable clicking inside a div with CSS or JavaScript, we can set the pointer-events CSS property to none . Also, we can add a click event listener to the div and then call event. preventDefault inside.
The onclick event occurs when the user clicks on an element.
To trigger a click button on ENTER key, We can use any of the keyup(), keydown() and keypress() events of jQuery. keyup(): This event occurs when a keyboard key is released. The method either triggers the keyup event, or to run a function when a keyup event occurs.
This is largely because lots of authors have historically written code using click events while forgetting to account for users who don't click (whether because they prefer to use a keyboard to navigate, have a disability which makes it hard to use a pointing device, or whatever other reason).
The behaviour is documented in the HTML specification:
Certain elements in HTML have an activation behavior, which means that the user can activate them. This triggers a sequence of events dependent on the activation mechanism, and normally culminating in a click event, as described below.
…
For accessibility, the keyboard’s Enter and Space keys are often used to trigger an element’s activation behavior.
It then goes on to explain the steps in detail.
Because for keyboard users (where a mouse is not available), when a button is in focus and you press Enter (possibly Space as well) it simulates a click event.
This is the browser's accessibility support which most, if not all, browsers provide.
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