50 lines
1.4 KiB
HTML
50 lines
1.4 KiB
HTML
|
<script>
|
||
|
function toggleDropdown(toggle, open) {
|
||
|
let parentElement = toggle.parentNode;
|
||
|
let dropdown = document.getElementById(toggle.getAttribute('aria-controls'));
|
||
|
dropdown.setAttribute('aria-hidden', !open);
|
||
|
|
||
|
if (open) {
|
||
|
parentElement.classList.add('is-active');
|
||
|
} else {
|
||
|
parentElement.classList.remove('is-active');
|
||
|
}
|
||
|
}
|
||
|
|
||
|
function closeAllDropdowns(toggles) {
|
||
|
toggles.forEach(function (toggle) {
|
||
|
toggleDropdown(toggle, false);
|
||
|
});
|
||
|
}
|
||
|
|
||
|
function handleClickOutside(toggles, containerClass) {
|
||
|
document.addEventListener('click', function (event) {
|
||
|
let target = event.target;
|
||
|
|
||
|
if (target.closest) {
|
||
|
if (!target.closest(containerClass)) {
|
||
|
closeAllDropdowns(toggles);
|
||
|
}
|
||
|
}
|
||
|
});
|
||
|
}
|
||
|
|
||
|
function initNavDropdowns(containerClass) {
|
||
|
let toggles = [].slice.call(document.querySelectorAll(containerClass + ' [aria-controls]'));
|
||
|
|
||
|
handleClickOutside(toggles, containerClass);
|
||
|
|
||
|
toggles.forEach(function (toggle) {
|
||
|
toggle.addEventListener('click', function (e) {
|
||
|
e.preventDefault();
|
||
|
|
||
|
const shouldOpen = !toggle.parentNode.classList.contains('is-active');
|
||
|
closeAllDropdowns(toggles);
|
||
|
toggleDropdown(toggle, shouldOpen);
|
||
|
});
|
||
|
});
|
||
|
}
|
||
|
|
||
|
initNavDropdowns('.p-navigation__item--dropdown-toggle');
|
||
|
</script>
|