Skip to content

Instantly share code, notes, and snippets.

@aFarkas
Last active August 20, 2020 10:49
Show Gist options
  • Save aFarkas/a7e0d85450f323d5e164 to your computer and use it in GitHub Desktop.
Save aFarkas/a7e0d85450f323d5e164 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);
@nikiedev
Copy link

nikiedev commented Aug 26, 2018

Does it work in Edge and IE ? Please, make an example of use for menu with such a structure:

Or all I need is just to include this file to the html ?

@dudewad
Copy link

dudewad commented Oct 1, 2018

Did you test this? Focus events don't bubble, are you sure this will work?

@shendrick
Copy link

Did you test this? Focus events don't bubble, are you sure this will work?

The true in as the third argument means that it listens for it in the capture phase. https://javascript.info/bubbling-and-capturing

@hamsterbacke23
Copy link

would it be possible to make a repo with a license out of this?

@zizoclimbs
Copy link

I tried it and It works fine in all browsers. Thanks a lot :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment