How to Trigger a Button Click on Keyboard “Enter” With JavaScript

As a web developer, you often have to create interactions that respond to a user’s actions on a page.

One common example is triggering a button click when the user presses the “Enter” key on their keyboard.

This enhances the user experience and makes your website more accessible to people with disabilities.

In this tutorial, we will explore how to trigger a button click on the keyboard “Enter” key with JavaScript.


HTML Markup for the Button

Before we start writing the JavaScript code, let’s create the HTML markup for the button.

You can create a button in HTML using the “button” element.

In the following example, we are creating a button with the text “Click Me” and giving it an ID of “myButton”:

<button id="myButton">Click Me</button>

Adding an Event Listener to the Document

To trigger the button click on the “Enter” key, we need to add an event listener to the document.

This event listener will listen for the “keydown” event and check if the key pressed is the “Enter” key. If it is, it will trigger the button click.

document.addEventListener("keydown", function(event) {
  if (event.code === "Enter") {
    document.getElementById("myButton").click();
  }
});

In this code, we are using the “addEventListener” method on the “document” object to listen for the “keydown” event.

This event is fired when the user presses a key on the keyboard.

The function passed to the “addEventListener” method takes an event object as an argument, which contains information about the event, such as the type of event and the key that was pressed.

In the function, we are using the “if” statement to check if the key that was pressed was the “Enter” key.

The “event.code” property contains the code for the key that was pressed. The “Enter” key has a code of “Enter”.

If the “Enter” key was pressed, we use the “document.getElementById” method to get the button element by its ID and then trigger a click on it using the “click” method.

And that’s it! Now, when the user presses the “Enter” key, the button will be triggered as if it were clicked with a mouse.


Conclusion

In this article, we have seen how to trigger a button click on the keyboard “Enter” key with JavaScript.

By using an event listener on the document and checking for the “Enter” key, you can make your website more user-friendly and accessible.

By adding this functionality, you can provide a better experience for your users and make your website stand out from the rest.