Yev Spektor

@yev_yev_yev

One line of code to remove :focus blue outline and keep accessibility

Everyone encounters this problem every time they make a web page with a button… The odd and out of place blue outline around a button after it is clicked [see below]

After clicking a button, the blue outline appears to indicate that it is in focus.

One approach is to remove the outline with css:

Do not do this!

The purpose of the outline is to improve website accessibility to those with disabilities or those who are navigating with only a keyboard, so we cannot just get rid of it altogether. We want to remove the outline only after the button is pressed.

If you look around online, there are many overly complicated solutions that detect if the button is highlighted from a click or from a tab keyboard press and adjust the css/classname accordingly. There are also some experimental CSS features that seek to solve this problem, but they are not compatible with most browsers yet.

A simple solution does exist! We can remove focus by calling the blur() function on the button after a submit event 🎉

event.target.submit.blur() removes focus after a submit event

And there you have it… An 1-line solution to remove the blue outline after a button press, while keeping accessibility features.

Topics of interest

More Related Stories