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.
The method should:
document.activeElement
.(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
}
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!)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With