Proposal: focus({forceVisible:true})

Currently when setting focus programmatically to an element with focus(), there is no way to instruct the browser to apply :focus-visible styling to it.

This can be problematic when using HTML-over-the-wire technologies like Hotwire or Htmx, where the focused element may be replaced with a new one, and the new one is given focus. If the initial element was showing a focus ring via :focus-visible styles, that styling will go away for the new element, because the browser has decided that it wasn’t necessary.

focus() currently supports passing an object with preventScroll:true to prevent the browser from scrolling to the focused element. I propose that the object should support an additional forceVisible key, which can be set to true to force :focus-visible styling on the element.

1 Like

Here’s a related discussion from the :focus-visible polyfill: Should :focus-visible match when returning focus or programmatically focusing? · Issue #88 · WICG/focus-visible · GitHub

I think it kinda shows that it’s not possible for the browser/polyfill to always know the right answer on what to do about :focus-visible, and there are cases where we need to be able to explicitly enable it.

You might have better luck sharing your idea on the web standards form ( This form focuses on the core language - the stuff that's common between all implementations of JavaScript (node, browsers, etc).

1 Like

Thanks for the tip! Posted here: Ability to explicitly set :focus-visible from focus() - APIs - WICG

1 Like