Objectif: créer un widget Toggle flexible dont le rôle sera uniquement d’affiche/masquer des éléments du DOM lorsque les utilisateurs interagissent avec un autre élément d’interface (bouton, checkbox, autre…).
Source: Marking elements expandable using aria-expanded. Exemple d’utilisation sur l’élément HTML Button. Exemple d’utilisation sur l’élément HTML Checkbox.
Exemple d’utilisation sur l’élément HTML Checkbox:
Source: https://www.accessibility-developer-guide.com/.
1 2 3 4 5 6 7 |
<p> Please click the following checkbox. </p> <input id="checkbox" type="checkbox" /><label for="checkbox">Show tooltip</label> <div hidden="" id="tooltip"> Thanks for toggling! Please click again to hide me. </div> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
;(function () { $(document).ready(function () { var $checkbox, $tooltip $checkbox = $('input') $tooltip = $('#tooltip') return $checkbox.change(() => { if ($tooltip.attr('hidden') === 'hidden') { return $tooltip.removeAttr('hidden') } else { return $tooltip.attr('hidden', true) } }) }) }.call(this)) |
Fichier wcag-toggle.js
:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
// Source: https://www.accessibility-developer-guide.com/examples/sensible-aria-usage/expanded/ define([ 'jquery', 'jquery-ui-modules/widget' ], function($) { 'use strict'; $.widget('mage.wcagToggle', { options: { toggleableElement: '' }, /** * Create widget * @private */ _create: function() { // console.log("%c wcagToggle", "background: yellow"); this.element.on('click', $.proxy(this._toggleOnOff, this)); // ...is similar to: // this.element.on('click', this._toggleOnOff.bind(this)); }, /** * Toggle On/Off * @private */ _toggleOnOff: function() { if ($(this.options.toggleableElement).attr('hidden') === 'hidden') { $(this.options.toggleableElement).removeAttr('hidden'); this.element.attr('aria-expanded', true); } else { $(this.options.toggleableElement).attr('hidden', true); this.element.attr('aria-expanded', false); } } }); return $.mage.wcagToggle; }); |
Fichier PHTML
:
Partie DOM (attention, je mets juste les grandes lignes). Se référer à l’example de code proposé par le site source.
1 2 3 4 5 6 7 |
<div class="field choice newsletter"> <input type="checkbox" id="is_subscribed" /> <label for="is_subscribed" class="label"></label> </div> <div id="is_subscribed_is_checked" hidden=""> </div> |
1 2 3 4 5 6 7 8 9 |
<script type="text/x-magento-init"> { "#is_subscribed": { "wcagToggle": { "toggleableElement": "#is_subscribed_is_checked" } } } </script> |
On n’oublie pas la déclaration (à votre propre sauce) dans un fichier requirejs-config.js
:
1 2 3 4 5 6 7 |
var config = { map: { '*': { wcagToggle: 'Magento_Theme/js/widgets/wcag-toggle' } } }; |