From 6437acf2b671439bdef3199511dd3761aa187090 Mon Sep 17 00:00:00 2001 From: Nicolas Coden Date: Thu, 12 Apr 2018 23:51:12 +0200 Subject: [PATCH] fix: improve id detection/replacment for Toggler `aria-controls` attribute Changes: * Only add the id if it does not exist in `aria-contolers` with better RegExp detection * Use ES6 features to simplify code * Add comments --- js/foundation.toggler.js | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/js/foundation.toggler.js b/js/foundation.toggler.js index f49e50ef6..ec630ac9d 100644 --- a/js/foundation.toggler.js +++ b/js/foundation.toggler.js @@ -3,6 +3,7 @@ import $ from 'jquery'; import { Motion } from './foundation.util.motion'; import { Plugin } from './foundation.core.plugin'; +import { RegExpEscape } from './foundation.core.utils'; import { Triggers } from './foundation.util.triggers'; /** @@ -58,19 +59,19 @@ class Toggler extends Plugin { this.className = input[0] === '.' ? input.slice(1) : input; } - // Add ARIA attributes to triggers + // Add ARIA attributes to triggers: var id = this.$element[0].id, - $triggers = $(`[data-open~="${id}"], [data-close~="${id}"], [data-toggle~="${id}"]`), - that = this; + $triggers = $(`[data-open~="${id}"], [data-close~="${id}"], [data-toggle~="${id}"]`); - $triggers.each(function(index, element) { - var $this = $(element); + // - aria-expanded: according to the element visibility. + $triggers.attr('aria-expanded', !this.$element.is(':hidden')); + // - aria-controls: adding the element id to it if not already in it. + $triggers.each((index, trigger) => { + const $trigger = $(trigger); + const controls = $trigger.attr('aria-controls') || ''; - //make sure not to duplicate id in aria-controls - $this.attr({ - 'aria-controls': `${$this.attr('aria-controls') ? $this.attr('aria-controls').replace(id, '') : ''} ${id}`.trim(), - 'aria-expanded': that.$element.is(':hidden') ? false : true - }); + const containsId = new RegExp(`\\b${RegExpEscape(id)}\\b`).test(controls); + if (!containsId) $trigger.attr('aria-controls', controls ? `${controls} ${id}` : id); }); } -- 2.47.2