]> git.ipfire.org Git - thirdparty/foundation/foundation-sites.git/commitdiff
fix: improve id detection/replacment for Toggler `aria-controls` attribute 11167/head
authorNicolas Coden <nicolas@ncoden.fr>
Thu, 12 Apr 2018 21:51:12 +0000 (23:51 +0200)
committerNicolas Coden <nicolas@ncoden.fr>
Thu, 12 Apr 2018 21:51:12 +0000 (23:51 +0200)
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

index f49e50ef6b5bac883abaad35d9cca5acdb973164..ec630ac9d05ef95b561fa185c8b13fcc64e870fb 100644 (file)
@@ -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);
     });
   }