From 53a58bc284361f32fd30cba4545d63b6d2350e1c Mon Sep 17 00:00:00 2001 From: Eric Bremner <ebremner@uwaterloo.ca> Date: Mon, 25 Jul 2022 10:16:14 -0400 Subject: [PATCH] ISTWCMS-5656: fixing js for tabs --- src/patterns/04-components/tabs/tabs.js | 74 ++++++++++++++++++++++++- 1 file changed, 72 insertions(+), 2 deletions(-) diff --git a/src/patterns/04-components/tabs/tabs.js b/src/patterns/04-components/tabs/tabs.js index 8b9fc0dd..bbad2810 100644 --- a/src/patterns/04-components/tabs/tabs.js +++ b/src/patterns/04-components/tabs/tabs.js @@ -1,5 +1,6 @@ /** * @file + * JS for tabs. */ (function ($, Drupal) { @@ -10,18 +11,87 @@ $('.uw-contact-expand-all').click(function () { $('.uw-contact details').each(function () { - console.log($(this)); $(this).attr('open', ''); }); }); $('.uw-contact-collapse-all').click(function () { $('.uw-contact details').each(function () { - console.log($(this)); $(this).removeAttr('open'); }); }); + /** + * Change tabs. + * @param {e} e The event. + * @returns {null}. + */ + function changeTabs(e) { + const target = e.target; + const parent = target.parentNode; + const grandparent = parent.parentNode; + + // Remove all current selected tabs. + parent + .querySelectorAll('[aria-selected="true"]') + .forEach(t => t.setAttribute('aria-selected', false)); + + // Set this tab as selected. + target.setAttribute('aria-selected', true); + + // Hide all tab panels. + grandparent + .querySelectorAll('[role="tabpanel"]') + .forEach(p => p.setAttribute('hidden', true)); + + // Show the selected panel. + grandparent.parentNode + .querySelector(`#${target.getAttribute('aria-controls')}`) + .removeAttribute('hidden'); + } + + window.addEventListener('DOMContentLoaded', () => { + const tabs = document.querySelectorAll('[role="tab"]'); + const tabList = document.querySelector('[role="tablist"]'); + + if (tabs.length === 0) { + return; + } + + // Add a click event handler to each tab. + tabs.forEach(tab => { + tab.addEventListener('click', changeTabs); + }); + + // Enable arrow navigation between tabs in the tab list. + let tabFocus = 0; + + tabList.addEventListener('keydown', e => { + + // Move right. + if (e.keyCode === 39 || e.keyCode === 37) { + tabs[tabFocus].setAttribute('tabindex', -1); + if (e.keyCode === 39) { + tabFocus++; + // If we're at the end, go to the start. + if (tabFocus >= tabs.length) { + tabFocus = 0; + } + } + // Move left. + else if (e.keyCode === 37) { + tabFocus--; + // If we're at the start, move to the end. + if (tabFocus < 0) { + tabFocus = tabs.length - 1; + } + } + + tabs[tabFocus].setAttribute('tabindex', 0); + tabs[tabFocus].focus(); + } + }); + }); }); } }; -- GitLab