Reputation: 13
<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.
Upvotes: 1
Views: 51
Reputation: 63
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();
});
Upvotes: 0
Reputation: 662
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>
Upvotes: 0