Skip to content

Instantly share code, notes, and snippets.

@kartikprabhu
Created July 22, 2017 23:09
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 kartikprabhu/45528a06915ac2d92b1ec83084b31b84 to your computer and use it in GitHub Desktop.
Save kartikprabhu/45528a06915ac2d92b1ec83084b31b84 to your computer and use it in GitHub Desktop.
link aware progressive disclosure
// modified from https://adactio.com/journal/10365
// Licensed under a CC0 1.0 Universal (CC0 1.0) Public Domain Dedication
// http://creativecommons.org/publicdomain/zero/1.0/
(function (win, doc) {
'use strict';
if (!doc.querySelectorAll || !win.addEventListener) {
// doesn't cut the mustard.
return;
}
// show
function showToggle(toggle, togglecontent){
togglecontent.setAttribute('aria-hidden', 'false');
toggle.setAttribute('aria-expanded', 'true');
}
// hide
function hideToggle(toggle, togglecontent){
togglecontent.setAttribute('aria-hidden', 'true');
toggle.setAttribute('aria-expanded', 'false');
}
// set toggle
function setToggle(){
for (var toggles = doc.querySelectorAll('[aria-controls]'), index = 0, toggle; (toggle = toggles[index]); ++index) {
var toggleID = toggle.getAttribute('aria-controls');
if (doc.getElementById(toggleID)) {
var togglecontent = doc.getElementById(toggleID),
id = location.href.match(/#((?:#|%23)?)(.+)/) || [0,'',''],
islinked = false;
/* find if togglecontent or any children are fragment targets or fragmentioned */
if(toggleID == id[1]+id[2] || togglecontent.hasAttribute("fragmention") ){
islinked = true;
}else{
try{
islinked = togglecontent.querySelectorAll('#'+id[1]+id[2]).length;
}catch(e){
islinked = togglecontent.querySelectorAll('[fragmention]').length;
}
}
if(islinked){
showToggle(toggle,togglecontent);
}else{
hideToggle(toggle,togglecontent);
togglecontent.setAttribute('tabindex', '-1');
}
toggle.setAttribute('aria-hidden', 'false');
}
}
}
// toggle show and hide
function toggle(ev) {
ev = ev || win.event;
var target = ev.target || ev.srcElement;
if (target.hasAttribute('aria-controls')) {
var toggleID = target.getAttribute('aria-controls');
if (doc.getElementById(toggleID)) {
ev.preventDefault();
var togglecontent = doc.getElementById(toggleID);
if (togglecontent.getAttribute('aria-hidden') == 'true') {
showToggle(target, togglecontent);
// togglecontent.focus(); https://github.com/edenspiekermann/a11y-toggle/issues/10
} else {
hideToggle(target, togglecontent);
}
}
}
}
doc.addEventListener('click', toggle, false);
for(var links = doc.querySelectorAll('a'), index = 0, link; (link = links[index]); ++index) {
link.addEventListener('click', setToggle, false);
}
// add listeners for hashchange and readystate
win.addEventListener("hashchange", setToggle, false);
doc.addEventListener('readystatechange', setToggle, false);
setToggle();
}(this, this.document));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment