1 window.addEventListener('load', function() {
2 // Get relevant elements and collections
3 const tabbed = document.querySelector('.tabbed');
4 const tablist = tabbed.querySelector('ul');
5 const tabs = tablist.querySelectorAll('a');
6 const panels = tabbed.querySelectorAll('[id^="section"]');
8 // The tab switching function
9 const switchTab = (oldTab, newTab) => {
11 // Make the active tab focusable by the user (Tab key)
12 newTab.removeAttribute('tabindex');
13 // Set the selected state
14 newTab.setAttribute('aria-selected', 'true');
15 newTab.classList.add('active');
16 oldTab.removeAttribute('aria-selected');
17 oldTab.setAttribute('tabindex', '-1');
18 oldTab.classList.remove('active');
19 // Get the indices of the new and old tabs to find the correct
20 // tab panels to show and hide
21 let index = Array.prototype.indexOf.call(tabs, newTab);
22 let oldIndex = Array.prototype.indexOf.call(tabs, oldTab);
23 panels[oldIndex].hidden = true;
24 panels[index].hidden = false;
27 // Add the tablist role to the first <ul> in the .tabbed container
28 tablist.setAttribute('role', 'tablist');
30 // Add semantics are remove user focusability for each tab
31 Array.prototype.forEach.call(tabs, (tab, i) => {
32 tab.setAttribute('role', 'tab');
33 tab.setAttribute('id', 'tab' + (i + 1));
34 tab.setAttribute('tabindex', '-1');
35 // tab.setAttribute('class', 'active');
36 tab.parentNode.setAttribute('role', 'presentation');
38 // Handle clicking of tabs for mouse users
39 tab.addEventListener('click', e => {
41 let currentTab = tablist.querySelector('[aria-selected]');
42 if (e.currentTarget !== currentTab) {
43 switchTab(currentTab, e.currentTarget);
47 // Handle keydown events for keyboard users
48 tab.addEventListener('keydown', e => {
49 // Get the index of the current tab in the tabs node list
50 let index = Array.prototype.indexOf.call(tabs, e.currentTarget);
51 // Work out which key the user is pressing and
52 // Calculate the new tab's index where appropriate
53 let dir = e.which === 37 ? index - 1 : e.which === 39 ? index + 1 : e.which === 40 ? 'down' : null;
56 // If the down key is pressed, move focus to the open panel,
57 // otherwise switch to the adjacent tab
58 dir === 'down' ? panels[i].focus() : tabs[dir] ? switchTab(e.currentTarget, tabs[dir]) : void 0;
63 // Add tab panel semantics and hide them all
64 Array.prototype.forEach.call(panels, (panel, i) => {
65 panel.setAttribute('role', 'tabpanel');
66 panel.setAttribute('tabindex', '-1');
67 let id = panel.getAttribute('id');
68 panel.setAttribute('aria-labelledby', tabs[i].id);
72 // Initially activate the first tab and reveal the first tab panel
73 tabs[0].removeAttribute('tabindex');
74 tabs[0].setAttribute('aria-selected', 'true');
75 tabs[0].setAttribute('class', 'active');
76 panels[0].hidden = false;