Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Last active November 29, 2020 17:27
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WebReflection/c5d9b4d83b7c566773f2874ade7fb0d7 to your computer and use it in GitHub Desktop.
Save WebReflection/c5d9b4d83b7c566773f2874ade7fb0d7 to your computer and use it in GitHub Desktop.
A basic way to make any element accessible and anchorable on any page.

Anchorable Headers / Elements

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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment