Hiding focus on click

Tutorial:

Hiding focus on click

Accessibility is a big deal in the industry these days, it should be a high priority of every developer to make sure their work is as accessible as it can be. Taking the time to learn about how you can improve your code to make it more accessible is crucial.

If you watch the clip below, you’ll see focus rings appearing upon clicking with the mouse.

You can see how it can look quite ugly and is totally unnecessary since If the user is able to see enough to click on something, then they don’t need the added focus ring to guide them further.

So how do we fix this?

There are a handful of different ways that I’ve seen people accomplish this task. You can do it in just HTML and CSS by adding a span and tabindex to the link. But that sounds like too much effort for a lazy developer like me, and definitely leaves too much room for error because you could easily forget to add the fix to some links and not have consistency.

I much prefer this simple catch-all method which I’ll explain below.

CSS

Firstly, let’s add some CSS that will hide the focus styles when the body has a class of using-mouse set on itself. You will most likely only need to add outline:none for your CSS, I just have some animation set on mine that I remove as well.

body.using-mouse :focus {
  outline: none;
  animation: none;
}

JS

Next up we are simply going to be adding and removing that same class using-mouse to the body tag, depending on whether the user is clicking, or using the tab key to navigate the page.
This is done by creating two event listeners and attaching them to the body so that they can listen out for everything on the page.

document.body.addEventListener("mousedown", () => {
  document.body.classList.add("using-mouse");
});
document.body.addEventListener("keydown", ({ key }) => { 
  if (key === "Tab") { 
    document.body.classList.remove("using-mouse"); 
  } 
});

If you enjoyed this post, be sure to check out some of my other CSS blog posts, such as Incrementing numbers in CSS, Centring in CSS, Useful CSS Generators.

Previous post:

Next post:

Leave a Reply

Your email address will not be published. Required fields are marked *