Skip to content

Instantly share code, notes, and snippets.

@brayhoward
Created August 17, 2016 18:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brayhoward/fbd7ad32bf92e346322f6586ed80b3f2 to your computer and use it in GitHub Desktop.
Save brayhoward/fbd7ad32bf92e346322f6586ed80b3f2 to your computer and use it in GitHub Desktop.
Skip navigation.
body
header
a#skip-nav(href="#main-content")
nav
...
#main-content
a#skip-nav {
position: absolute;
top:-10%;
left:25%;
&:active, &:focus, &:hover {
top: 0;
}
}
// This script is looking for a link with the id of "skip-nav"
// On click it will force the browser to change focus to the chosen element
// a(href="#whatevIDHere" id="skip-nav")
ready( () => {
// bind a click event to the 'skip' link
document.getElementById("skip-nav").addEventListener("click", event => {
let self = event.srcElement;
// strip the leading hash and get Element we're skipping to
let skipTo = document.getElementById(self.href.split('#')[1])
// Setting 'tabindex' to -1 takes an element out of normal
// tab flow but allows it to be focused via javascript
skipTo.setAttribute('tabindex', -1)
addMultipleListeners(skipTo, 'blur focusout', () => {
// when focus leaves this element,
// remove the tabindex attribute
skipTo.removeAttribute('tabindex');
}).focus(); // focus on the content container
});
}
);
// Jquery like functions
//document.ready(fn)
function ready(fn) {
if (document.readyState != 'loading'){
fn();
} else {
document.addEventListener('DOMContentLoaded', fn);
}
}
// on(eventsString, fn)
function addMultipleListeners(element, events, fn) {
events.split(" ").forEach(event => {
element.addEventListener(event, fn);
});
return element
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment