Skip to content

Instantly share code, notes, and snippets.

@geraldalewis
Created April 14, 2017 15:38
Show Gist options
  • Save geraldalewis/d69d043ab8affc63a3c18fcf3940f260 to your computer and use it in GitHub Desktop.
Save geraldalewis/d69d043ab8affc63a3c18fcf3940f260 to your computer and use it in GitHub Desktop.
Smart styled <button> focus ring behavior
function initializeRinger(){
var pressedAt = 0;
document.removeEventListener('DOMContentLoaded', initializeRinger);
function checkRing(target){
if (!target.classList.contains('ringer')) return;
if (target.classList.contains('ringer-no-ring')) return;
target.classList.add('ringer-no-ring');
}
function onpress(event){
pressedAt = Date.now();
}
function onfocus(event){
if ((Date.now() - pressedAt) < 100) checkRing(event.target);
}
function onblur(event){
var target = event.target;
if (target.classList.contains('ringer-no-ring')) {
target.classList.remove('ringer-no-ring');
}
}
document.body.addEventListener('mousedown', onpress, true);
document.body.addEventListener('focus', onfocus, true);
document.body.addEventListener('blur', onblur, true);
}
if (document.readyState === 'complete') initializeRinger();
else document.addEventListener('DOMContentLoaded', initializeRinger, false);
@geraldalewis
Copy link
Author

Use it by adding ringer to a button's class list:

<button class="styled-button ringer">Button</button>

and adding the following css:

.ringer {
}
.ringer-no-ring {
  outline: none;
}

Caveats

  • Not sure if/how it works on mobile devices.
  • Applying style via the :focus pseudo-class will yield unexpected results (the style changes will persist even after the button is released on mouseup).

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