Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pragrammatically focus on HTML element without outline?

Caution: :focus { outline: none } should not be the answer as it also prevents outline when navigating by tab key

Clicking a button does not show outline but the button becomes document.activeElement (JSFiddle). I want to mimic this behavior without mouse clicking.

enter image description here

The method should:

  1. make the element as document.activeElement.
  2. not cause outline
  3. still allow outline when pressing keyboard tab key

(If anyone asks, my current intention is to focus a modal dialog and return the focus to the previous focused element when the dialog is closed. This requires preventing outline for seamless experience.)

pseudo code:

showDialog();

function whenDialogClosed() {
  previouslyFocused.focus(); // should not display outline
}
like image 290
Kagami Sascha Rosylight Avatar asked Oct 30 '22 22:10

Kagami Sascha Rosylight


1 Answers

CSS finally got an answer by adding a pseudo-class :focus-visible that activates exactly when browser decides to do.

For this reason, modern browsers apply simple heuristics to determine whether or not to apply their default focus styling. In general, if an element received focus as a result of a mouse/pointer click, browsers will suppress their default focus indication.

As of 2021, all modern browsers support this, however if you need to support older browsers, use a polyfill and do this:

/*
 * .js-focus-visible is automatically added to document.body
 * to ensure the rules run only in JS-supported environment
 */

.js-focus-visible .your-selector:focus:not(.focus-visible) { outline: none }

Demo:

focusrandom.addEventListener("click", () => {
  const num = Math.ceil(Math.random() * 5);
  const button = document.getElementById(`button${num}`);
  button.focus();
});
wofocusrandom.addEventListener("click", () => {
  const num = Math.ceil(Math.random() * 5);
  const button = document.getElementById(`wobutton${num}`);
  button.focus();
});
.js-focus-visible .apply button:focus:not(.focus-visible) {
  outline: none;
}
<script src="https://unpkg.com/focus-visible"></script>
<p class="apply">
  With focus-visible:
  <button id="button1">1</button>
  <button id="button2">2</button>
  <button id="button3">3</button>
  <button id="button4">4</button>
  <button id="button5">5</button>
</p>
<p>
  Without focus-visible:
  <button id="wobutton1">1</button>
  <button id="wobutton2">2</button>
  <button id="wobutton3">3</button>
  <button id="wobutton4">4</button>
  <button id="wobutton5">5</button>
</p>

<button id="focusrandom">Focus random button</button>
<button id="wofocusrandom">Focus random button without focus-visible</button>

(From https://stackoverflow.com/a/50571098/2460034. Thank you Aaron!)

like image 91
Kagami Sascha Rosylight Avatar answered Nov 12 '22 16:11

Kagami Sascha Rosylight