Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a `click` event get triggered on my <button> when I press Enter on it?

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?

like image 482
Vincent Avatar asked Jan 07 '19 11:01

Vincent


People also ask

How can you avoid button click event when Enter key is pressed in a text box?

Solution 1function (event) { if (event. which == 13 || event. keyCode == 13) { //code to execute here return false; } return true; }); Implement it according to your need.

How do I turn off event clicks?

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.

When a user clicks a button which event is triggered?

The onclick event occurs when the user clicks on an element.

How do you trigger click event on pressing Enter key?

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.


2 Answers

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.

like image 175
Quentin Avatar answered Oct 05 '22 23:10

Quentin


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.

like image 44
Adrian Avatar answered Oct 06 '22 01:10

Adrian