I’m trying to remove the focus state of a button once it is clicked. The issue is once I click a button and after that instead of clicking on anywhere else if I just press ENTER the click event on that button works again.
I tried adding outline: none
to the CSS but this is not removing the actual functionality of the button on focused state.
What can be the solution for this?
function test() {
console.log(1)
}
/** Many solutions mentioned this but this is just removing the view state */
button {
outline: none
}
<button type="button" onclick="test()">Click</button>
4
Answers
You can
blur
focus by calling following insidetest
fn –The issue you’re encountering arises because, when a button is clicked, it gains focus by default. When you press ENTER, the onclick event is triggered again because the button still retains focus.
To prevent this behavior, you can explicitly remove focus from the button after it is clicked. fix to your code:
for global level use it like this:
Here, remove the focus after the element is clicked.
You said you have hundreds of buttons so this setup can be used for that, you add one event listener on a container element, and only do the work if the event was triggered by one of the elements that you need.
Check the MDN events documentation for a better understanding of propagation, bubbling, e.target, all that.
Remove the visible focus using the code below