From e4976689a97266c4fef99e5efc76565fca7242a0 Mon Sep 17 00:00:00 2001 From: Hugo Giraudel Date: Thu, 10 Mar 2016 17:17:01 +0100 Subject: [PATCH] Improved the script to automatically assign an id attribute to the toggle if not set --- a11y-toggle.js | 24 +++++++++++++++++++----- a11y-toggle.min.js | 2 +- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/a11y-toggle.js b/a11y-toggle.js index 69d0e38..349463f 100644 --- a/a11y-toggle.js +++ b/a11y-toggle.js @@ -1,4 +1,5 @@ -(function () { +(function () { + // Simple polyfill for Object.keys function objectKeys (object) { if (Object.keys) return Object.keys(object); @@ -11,24 +12,35 @@ var toggles = document.querySelectorAll('[' + namespace + ']'); var togglesMap = {}; + // Loop over the toggles for (var i = 0; i < toggles.length; i += 1) { var toggle = toggles[i]; var targetId = toggle.getAttribute(namespace); - togglesMap['#' + targetId] = toggle.id; + + // Set `id`, `aria-expanded` and `aria-controls` if not set yet + toggle.id || toggle.setAttribute('id', targetId + '-a11y-toggle'); toggle.hasAttribute('aria-expanded') || toggle.setAttribute('aria-expanded', false); toggle.hasAttribute('aria-controls') || toggle.setAttribute('aria-controls', targetId); + + // Map target `id` selector with toggle `id` + togglesMap['#' + targetId] = toggle.id; } var targetsList = objectKeys(togglesMap); var targets = targetsList.length && document.querySelectorAll(targetsList); var targetsMap = {}; + // Loop over targets for (var j = 0; j < targets.length; j += 1) { var target = targets[j]; var toggleId = togglesMap['#' + target.id]; - targetsMap[target.id] = target; + + // Set `aria-hidden` and `aria-labelledby` if not set yet target.hasAttribute('aria-hidden') || target.setAttribute('aria-hidden', true); target.hasAttribute('aria-labelledby') || (toggleId && target.setAttribute('aria-labelledby', toggleId)); + + // Map target `id` with target node for quick find on click event + targetsMap[target.id] = target; } document.addEventListener('click', function (event) { @@ -36,7 +48,9 @@ var target = targetsMap[toggle.getAttribute(namespace)]; var isExpanded = JSON.parse(toggle.getAttribute('aria-expanded')); - target && toggle.setAttribute('aria-expanded', !isExpanded); - target && target.setAttribute('aria-hidden', isExpanded); + if (target) { + toggle.setAttribute('aria-expanded', !isExpanded); + target.setAttribute('aria-hidden', isExpanded); + } }); }()); diff --git a/a11y-toggle.min.js b/a11y-toggle.min.js index b839602..8c7b819 100644 --- a/a11y-toggle.min.js +++ b/a11y-toggle.min.js @@ -1 +1 @@ -!function(){function t(t){if(Object.keys)return Object.keys(t);var e=[];for(var r in t)t.hasOwnProperty(r)&&e.push(r);return e}for(var e="data-a11y-toggle",r=document.querySelectorAll("["+e+"]"),a={},i=0;i