skip to Main Content
<body>
    <button id="aButton">A button</button>

    <script>
        document.querySelector("#aButton").addEventListener("click", () => {
            console.log("Button clicked!");
        })
    </script>
</body>

I have a simple button that logs "Button clicked!" to the console when it is clicked. If I click that button and then press the enter key, the button is clicked again and the "Button clicked!" message is logged to the console a second time. How can I stop that? I don’t want the button to be clicked via the enter key, because I will be using the enter key for other purposes.

2

Answers


  1. Here is how you can prevent default when clicked enter key:

    <body>
        <button id="aButton">A button</button>
    
        <script>
            const button = document.querySelector("#aButton");
    
            button.addEventListener("click", () => {
                console.log("Button clicked!");
            });
    
            button.addEventListener("keydown", (event) => {
                // Check if the pressed key is Enter (key code 13)
                if (event.keyCode === 13) {
                    // Prevent the default action (submitting the form)
                    event.preventDefault();
                    // Prevent the event from propagating further
                    event.stopPropagation();
                }
            });
        </script>
    </body>
    Login or Signup to reply.
  2. The button will be auto focused after you clicked it. And it will be triggered again after you press the Enter Key. You should add evt.currentTarget.blur(); to prevent this behavior.

    document.querySelector('#aButton').addEventListener('click', (evt) => {
      console.log('Button clicked!');
      evt.currentTarget.blur();
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search