Passing any element through this function, will make it navigable via keyboard.
function anchorAble(e) {
/*! (c) Andrea Giammarchi - ISC */
if ('currentTarget' in e) {
if (/^(?:32|13|undefined)$/.test(e.keyCode)) {
e.preventDefault();
e = e.currentTarget;
e.scrollIntoView({behavior: 'smooth'});
e = e.id || e.name;
if (location.hash != ('#' + e))
history.pushState(null, e, '#' + e);
}
}
else {
e.setAttribute('tabindex', 0);
if (!(e.id || e.name))
e.id = e.innerText
.replace(/\W/g, ' ')
.replace(/^\s+|\s+$/g, '')
.replace(/\s+/g, '-')
.toLowerCase();
e.addEventListener('click', anchorAble, !1);
e.addEventListener('keydown', anchorAble, !1);
e.classList.add('anchor-able');
}
}
The element with a .anchor-able
class should be decorated in way that it makes it obvious it's clickable.
This is just a basic example:
.anchor-able {
cursor: pointer;
}
.anchor-able::before {
content: '#';
margin: auto .3em;
font-size: small;
font-weight: bold;
opacity: 0;
transition: opacity .3s;
}
.anchor-able:hover::before,
.anchor-able:focus::before {
opacity: 1;
}