skip to Main Content

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.

button focus issue

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


  1. You can blur focus by calling following inside test fn –

    <script>function test() { console.log(1); document.activeElement?.blur?.(); }</script>
    
    
    Login or Signup to reply.
  2. 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:

    <style>
      button { 
        outline: none;
      }
    </style>
    
    <button type="button" onclick="test(this)">Click</button>
    
    <script>
      function test(button) {
        console.log(1);
        button.blur();
      }
    </script>

    for global level use it like this:

    <script>
      document.addEventListener('click', function (event) {
        if (event.target.tagName === 'BUTTON') {
          event.target.blur();
        }
      });
    </script>
    Login or Signup to reply.
  3. 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.

    window.addEventListener('click', (e) => {
      const target = e.target 
      if(!target.classList.contains('btn')) { return }
      console.log('click!')
      target.blur()
    })
    <button class="btn">Button</button>
    <button class="btn">Button</button>
    <button class="btn">Button</button>
    <button class="btn">Button</button>
    <button class="btn">Button</button>
    Login or Signup to reply.
  4. Remove the visible focus using the code below

       button:focus {
          outline: none;
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search