The question is fairly straightforward. I want to check if the browser supports focus-visible (:focus-visible
) or not using JavaScript. How can I do this?
Asked
Active
Viewed 781 times
1

darkhorse
- 8,192
- 21
- 72
- 148
2 Answers
1
console.log(selectorSupported(":focus-visible"))
function selectorSupported(selector){
var support, link, sheet, doc = document,
root = doc.documentElement,
head = root.getElementsByTagName('head')[0],
impl = doc.implementation || {
hasFeature: function() {
return false;
}
},
link = doc.createElement("style");
link.type = 'text/css';
(head || root).insertBefore(link, (head || root).firstChild);
sheet = link.sheet || link.styleSheet;
if (!(sheet && selector)) return false;
support = impl.hasFeature('CSS2', '') ?
function(selector) {
try {
sheet.insertRule(selector + '{ }', 0);
sheet.deleteRule(sheet.cssRules.length - 1);
} catch (e) {
return false;
}
return true;
} : function(selector) {
sheet.cssText = selector + ' { }';
return sheet.cssText.length !== 0 && !(/unknown/i).test(sheet.cssText) && sheet.cssText.indexOf(selector) === 0;
};
return support(selector);
};
all credit to https://gist.github.com/paulirish/441842 from Modernizr.

Rio A.P
- 1,313
- 13
- 20
1
Every browser that supports :focus-visible
also supports the CSS.supports()
API.
So this should work:
window.CSS && CSS.supports && CSS.supports("selector(:focus-visible)")
Or in ECMAScript 2020:
window.CSS?.supports?.("selector(:focus-visible)")

Richard Connamacher
- 3,115
- 19
- 21