Last active
September 7, 2022 16:53
-
-
Save nfreear/f2c7a078ebae3b5b4a9f6c8e7768a1ae to your computer and use it in GitHub Desktop.
A Javascript skip link that works on desktop and mobile.
This file contains 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
<!doctype html> <title> Skip link test </title> | |
<style> body { margin: 1rem auto; max-width: 32rem; } </style> | |
<div id="skip-link"><a href="#skip-link">Skip to content</a></div> | |
<header> | |
<p><a href="#my-header">My header</a>.</p> | |
</header> | |
<main> | |
<h1> Skip link test </h1> | |
<p><a href="#hello-main-body">Hello! Main body text</a></p> | |
<p> A Javascript skip link that works on desktop and mobile. </p> | |
</main> | |
<script> | |
function skipLink () { | |
const link = document.querySelector('#skip-link a'); | |
const elm = document.querySelectorAll('h1:not([hidden]), h2:not([hidden])'); // Was: 'h1:visible, h2:visible' (jQuery) | |
if (!elm.length) { | |
throw new Error('Skip-link target not found!'); | |
} | |
link.addEventListener('click', ev => { | |
ev.preventDefault(); | |
elm[0].setAttribute('tabindex', '-1'); | |
elm[0].focus(); | |
// TODO: scroll! | |
console.debug('Skip link click:', elm, ev); | |
}); | |
} | |
skipLink(); | |
</script> | |
<pre><small> | |
NDF, 07-Sep-2022. | |
* Your skip links are broken: https://axesslab.com/skip-links/, | |
* https://github.com/selfthinker/dokuwiki_template_writr/blob/master/js/skip-link-focus-fix.js, | |
</small></pre> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment