Search code examples
javascriptbuttoneventsenter

How to stop a button from being clicked again when I press the enter key after clicking it


<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.


Solution

  • 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();
    });