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