Skip to content

Instantly share code, notes, and snippets.

@zizoclimbs
Forked from aFarkas/focus-within.js
Created April 8, 2019 14:53
Show Gist options
  • Save zizoclimbs/df103b6240920d0b86d0bb9630cba236 to your computer and use it in GitHub Desktop.
Save zizoclimbs/df103b6240920d0b86d0bb9630cba236 to your computer and use it in GitHub Desktop.
simple focus-within polyfill
(function(window, document){
'use strict';
var slice = [].slice;
var removeClass = function(elem){
elem.classList.remove('focus-within');
};
var update = (function(){
var running, last;
var action = function(){
var element = document.activeElement;
running = false;
if(last !== element){
last = element;
slice.call(document.getElementsByClassName('focus-within')).forEach(removeClass);
while(element && element.classList){
element.classList.add('focus-within');
element = element.parentNode;
}
}
};
return function(){
if(!running){
requestAnimationFrame(action);
running = true;
}
};
})();
document.addEventListener('focus', update, true);
document.addEventListener('blur', update, true);
update();
})(window, document);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment