:focus-visible and JavaScript


Thanks to splendid browser support, utilizing :focus-visible is a thing now. We can finally have highly prominent focus styles for those who navigate our sites with a keyboard, and at the same time do not need to show visitors browsing with a mouse how prominent they are. The keyboard/mouse divide is a bit of a simplification, as there are more input devices out there. In general, web browsers have heuristics to figure out which focus style to apply, but surely how our visitor got to an interactive element will be taken into account.

Which made me wonder, what if it was not actually the visitor who moved the focus, but the site itself using JavaScript?

First thing I found was the “focus-visible“ CSS almanac entry on CSS-Tricks, which gave me a clue that the last thing a visitor does before JavaScript takes over plays a big role here:

Situation: A script causes focus to move from a :focus-visible element to another element
Does :focus-visible apply? Yes
Situation: A script causes focus to move from a non-:focus-visible element to another element
Does :focus-visible apply? No

Not being entirely satisfied with this, I created a little test page. Doing so, I’ve been able to confirm the above, and additionally I learned :focus-visible is also applied …

  • when a script moves focus on page load—a scenario where the web browser has a hard time figuring out which input device the visitor used beforehand;
  • when the target is an editable input field like input[type="text"] or textarea— in these cases the focus-visible style is always applied, input device does not matter.