Thursday, March 21, 2024

Triggering Button Click on with JavaScript on Enter Key Press

Must read


A technique you possibly can improve UX is to permit customers to work together together with your net software utilizing their keyboard. That is particularly useful in terms of kind inputs and buttons. On this Byte, we’ll discover methods to set off a button click on with JavaScript when the Enter secret is pressed.

Occasions in JavaScript

Occasions are a core a part of constructing interactive net purposes. They symbolize the consumer’s interplay with the webpage, comparable to clicks, key presses, mouse actions, and so forth. JavaScript gives a system to deal with these occasions, permitting us builders to create dynamic and interactive experiences.

onclick Occasion

The onclick occasion in JavaScript is triggered when a consumer clicks on a component. This occasion is commonly used to execute a operate when a button is clicked, like this:

<button onclick="alert('Hey, World!')">Click on me</button>

On this code snippet, each time the button is clicked, an alert field with the message ‘Hey, World!’ seems on the display.

onkeydown and onkeypress Occasions

Similar to onclick, the onkeydown and onkeypress occasions are triggered when a consumer interacts with a component. Nevertheless, as a substitute of a mouse click on, these occasions are fired when a consumer presses a key on their keyboard. The onkeydown occasion is triggered the second a secret is pressed down, whereas onkeypress is triggered when a secret is pressed and launched.

Let’s check out how this works:

<enter sort="textual content" onkeydown="console.log('Secret is pressed down')" onkeypress="console.log('Secret is pressed and launched')">

On this code snippet, each time a secret is pressed down within the enter discipline, “Secret is pressed down” is logged to the console. When the secret’s pressed and launched, “Secret is pressed and launched” is logged.

Observe: The principle distinction between onkeydown and onkeypress is that onkeydown can detect all keys, whereas onkeypress solely detects keys that produce a personality worth, like alphabets, numbers, and punctuation. This makes onkeydown extra appropriate for our use-case of detecting the Enter key press.

Why Set off Button Click on on Enter?

A key facet of fine consumer expertise is making certain that your web site or software isn’t solely simple to make use of, but in addition intuitive. One widespread conference that many customers are accustomed to is the flexibility to set off a button click on by urgent the Enter key. That is particularly necessary with kind submissions, the place customers could fill out a bunch of fields and naturally count on to submit the shape by urgent Enter, as a substitute of manually having clicking a submit button.

Triggering a button click on on Enter key press not solely improves the consumer expertise, but in addition enhances usability for customers who depend on keyboards for navigation, probably to both velocity up the method or as a result of bodily limitations.

Implementing Button Click on Set off on Enter Key Press

To implement this, we’ll want to make use of JavaScript, after all. Particularly, we’ll be utilizing JavaScript’s occasion dealing with to pay attention for the Enter key press after which set off the button click on.

HTML Setup

Let’s begin with a quite simple HTML kind with an enter discipline and a button:

<kind id="myForm">
  <enter sort="textual content" id="myInput" placeholder="Kind one thing...">
  <button id="myButton">Submit</button>

On this setup, we’ve got a kind with an id of “myForm”, an enter discipline with an id of “myInput”, and a button with an id of “myButton”.


Now, let’s add the JavaScript to set off the button click on on Enter key press. We’ll use the addEventListener technique to pay attention for the “keydown” occasion on the enter discipline. When the occasion is fired, we’ll test if the important thing pressed was Enter (key code 13), and in that case, we’ll set off the button click on utilizing the click on technique.

doc.getElementById('myInput').addEventListener('keydown', operate(occasion) {
  // Verify if Enter was pressed
  if (occasion.keyCode === 13) {
    // Stop the default motion
    // Set off the button click on
    doc.getElementById('myButton').click on();

We first get the enter discipline by its id utilizing doc.getElementById. We then add an occasion listener for the “keydown” occasion. Contained in the occasion listener, we test if the important thing code of the occasion is 13, which corresponds to the Enter key. Whether it is, we forestall the default motion utilizing occasion.preventDefault (which might be to submit the shape and refresh the web page), after which set off the button click on utilizing doc.getElementById('myButton').click on().

In the event you’re utilizing jQuery, you’d wanto to make use of one thing like this as a substitute:

$("#myInput").keyup(operate(occasion) {
    if (occasion.keyCode === 13) {
        $("#myButton").click on();

The code could be very related in construction, however it’s kind of extra compact and simpler to learn.

And there you will have it! With just some traces of JavaScript, we now enable customers to submit a kind by urgent the Enter key. Whereas this may appear to be a small element, it is these sorts of enhancements that may make an enormous distinction within the general consumer expertise.

Dealing with Occasion Effervescent and Propagation

Occasion effervescent is an idea in JavaScript the place an occasion triggers on the deepest doable aspect, after which triggers on mum or dad components in nesting order. Consequently, a mum or dad aspect can react to a baby aspect’s occasion. This could trigger sudden conduct while you’re attempting to set off a button click on on an Enter key press.

Think about the next code snippet:

  <div id="mum or dad">
    Dad or mum
    <button id="baby">Click on Me!</button>

    // Connect occasion listener to the kid aspect
    doc.getElementById("baby").onclick = operate(occasion) {
      alert("Little one Button Clicked!");

    // Connect occasion listener to the mum or dad aspect
    doc.getElementById("mum or dad").onclick = operate(occasion) {
      alert("Dad or mum Div Clicked!");

On this case, if you happen to click on on the kid aspect, the mum or dad div can even obtain the “onclick” occasion.

To stop this, you should utilize occasion.stopPropagation(). This prevents additional propagation of the present occasion within the capturing and effervescent phases.

Related Use-Circumstances

Triggering a button click on on an Enter key press is only one of many related use-cases. Let’s examine a number of others.

Type Submission on Enter Key Press

One widespread use-case for triggering occasions with the Enter secret is kind submission. By default, most browsers will submit a kind when the Enter secret is pressed, assuming the shape has a submit button. Nevertheless, there could also be cases the place you need to manually management this conduct utilizing JavaScript.

Think about the next HTML kind:

<kind id="myForm">
  <enter sort="textual content" id="title" placeholder="Enter your title">
  <enter sort="textual content" id="e-mail" placeholder="Enter your e-mail">
  <button sort="submit">Submit</button>

You may pay attention for the “keydown” occasion and test if the Enter secret is pressed. Whether it is, you possibly can manually submit the shape:

doc.getElementById('myForm').addEventListener('keydown', operate(occasion) {
  // Verify if Enter was pressed with out Shift, Ctrl, Alt, Caps
  if (occasion.key === 'Enter' && !occasion.shiftKey && !occasion.ctrlKey && !occasion.altKey && !occasion.capsLockKey) {

Observe: It might even be necessary to test for modifier keys like Shift, Ctrl, Alt, and Caps Lock. If these keys are pressed together with Enter, the shape shouldn’t be submitted. This enables customers to insert line breaks into textual content fields if wanted.

Triggering Different Occasions on Key Press

Past kind submission, there are numerous different occasions you may need to set off with a key press. For instance, you may need to set off a button click on when the House bar is pressed. Think about a button that toggles a lightbulb on and off:

<button id="lightSwitch">Toggle Gentle</button>

You may pay attention for the ‘keydown’ occasion and set off the button click on when the House bar is pressed:

doc.addEventListener('keydown', operate(occasion) {
  if (occasion.code === 'House') {
    doc.getElementById('lightSwitch').click on();

On this case, urgent the House bar could have the identical impact as clicking the button. The chances are countless, and you’ll set off just about any occasion with any key press.


On this Byte, we have explored methods to set off button clicks and different occasions with key presses in JavaScript. We have checked out methods to submit types with the Enter key and methods to set off button clicks with the House bar. We have additionally touched on potential points like occasion effervescent/propagation.

Supply hyperlink

More articles


Please enter your comment!
Please enter your name here

Latest article