Created
April 14, 2017 15:38
-
-
Save geraldalewis/d69d043ab8affc63a3c18fcf3940f260 to your computer and use it in GitHub Desktop.
Smart styled <button> focus ring behavior
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use it by adding
ringer
to a button's class list:and adding the following css:
Caveats
:focus
pseudo-class will yield unexpected results (the style changes will persist even after the button is released onmouseup
).