sector_megamenu-1.0.2/components/megamenu/root/root.js
components/megamenu/root/root.js
window.addEventListener('load', () => {
let openBody = null;
const megamenuBodyHandler = new CustomEvent('megamenuBodyHandler', {
bubbles: true, // Specifies whether the event bubbles up through the DOM or not
cancelable: true // Specifies whether the event is cancelable or not
});
const toggles = document.querySelectorAll('.mega-menu__toggle');
if (toggles.length === 0) {
return;
}
toggles.forEach((megaMenuToggle) => {
megaMenuToggle.addEventListener('click', ({ srcElement }) => {
toggles.forEach((toggle) => toggle.setAttribute('aria-expanded', 'false'));
const targetId = srcElement.getAttribute('aria-controls');
const action = openBody === targetId ? 'close' : 'open'
const target = document.getElementById(targetId);
megamenuBodyHandler.action = action;
if(!target) {
return;
}
target.dispatchEvent(megamenuBodyHandler);
openBody = action === 'open' ? targetId : null
srcElement.setAttribute('aria-expanded', action === 'open')
})
megaMenuToggle.addEventListener('megamenuRootButtonHandler', ({ srcElement }) => {
srcElement.setAttribute('aria-expanded', 'false');
openBody = null;
})
})
// esc key
document.addEventListener('keyup', function(event) {
if (event.key === 'Escape' || event.key === 'Esc') {
toggles.forEach((toggle) => {
toggle.setAttribute('aria-expanded', 'false')
})
openBody = null;
}
});
});