Skip to content

Commit

Permalink
Improved the script to automatically assign an id attribute to the to…
Browse files Browse the repository at this point in the history
…ggle if not set
  • Loading branch information
KittyGiraudel committed Mar 10, 2016
1 parent 123ef7f commit e497668
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 6 deletions.
24 changes: 19 additions & 5 deletions a11y-toggle.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
(function () {
(function () {
// Simple polyfill for Object.keys
function objectKeys (object) {
if (Object.keys) return Object.keys(object);

Expand All @@ -11,32 +12,45 @@
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) {
var toggle = event.target;
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);
}
});
}());
2 changes: 1 addition & 1 deletion a11y-toggle.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit e497668

Please sign in to comment.