Skip to content

Instantly share code, notes, and snippets.

@pentaphobe
Created April 27, 2018 01:55
Show Gist options
  • Save pentaphobe/bc6ed876f14d709c7c9046437a93041e to your computer and use it in GitHub Desktop.
Save pentaphobe/bc6ed876f14d709c7c9046437a93041e to your computer and use it in GitHub Desktop.
accessibility outline solution thoughts
/**
* Assumes all elements have had outline style removed
*/
;(() => {
let accessibilityMode = false;
let oldOutlineStyle;
let lastModifiedElement;
let mouseTimeoutHandle;
const saveStyles = el => {
oldOutlineStyle = el.style.outline;
lastModifiedElement = el;
}
const restoreStyles = el => {
el.style.outline = oldOutlineStyle;
}
const restoreLastElement = () => {
if (lastModifiedElement) {
restoreStyles(lastModifiedElement);
lastModifiedElement = undefined;
}
}
const removeInlineStyle = (el, styleName) => {
if (el.style.removeProperty) {
el.style.removeProperty(styleName);
} else {
el.style.removeAttribute(styleName);
}
}
document.addEventListener('keydown', () => {
clearTimeout(mouseTimeoutHandle);
accessibilityMode = true;
console.log('accessibilityMode', accessibilityMode);
}, true)
document.addEventListener('focus', (e) => {
clearTimeout(mouseTimeoutHandle);
restoreLastElement();
console.log('focus:');
if (accessibilityMode) {
console.log('-- update style for ', e.target);
saveStyles(e.target);
removeInlineStyle('outline');
}
}, true)
document.addEventListener('blur', (e) => {
clearTimeout(mouseTimeoutHandle);
console.log('blur:');
if (accessibilityMode) {
restoreStyles(e.target);
console.log('-- restore style for ', e.target);
}
}, true)
document.addEventListener('mousemove', (e) => {
// if we've a previously touched element, ensure it's restored
restoreLastElement();
// create a cancellable timeout
clearTimeout(mouseTimeoutHandle);
mouseTimeoutHandle = setTimeout( () => {
accessibilityMode = false;
console.log('accessibilityMode', accessibilityMode);
}, 100);
}, true)
})()
/**
* Alternative approach, assumes:
* - we never want outline when mouse-focused
* - all outline styles are applied already
*/
;(() => {
const removeInlineStyle = (el, styleName) => {
if (el.style.removeProperty) {
el.style.removeProperty(styleName);
} else {
el.style.removeAttribute(styleName);
}
}
const focusHandler = e => {
e.target.style.outline = 'none';
}
const blurHandler = e => {
removeInlineStyle(e, 'outline');
}
document.addEventListener('click', focusHandler, true);
document.addEventListener('blur', blurHandler, true);
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment