Submenu Collapse By Default 3rd Level
-
This code worked to collapse the 3rd level submenu while leaving parent menus expanded, this took hours to make right, hopefully saving someone some time.
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
const topLevelLinks = document.querySelectorAll('.mega-menu-item > .mega-menu-link');
const secondLevelLinks = document.querySelectorAll('.mega-menu-item-has-children > .mega-sub-menu > .mega-menu-item > .mega-menu-link');
// Ensure top-level menus are visible
topLevelLinks.forEach(link => {
const subMenu = link.nextElementSibling;
if (subMenu && subMenu.classList.contains('mega-sub-menu')) {
subMenu.style.display = 'block';
link.setAttribute('aria-expanded', 'true');
}
});
// Collapse second-level submenus by default
secondLevelLinks.forEach(link => {
const subMenu = link.nextElementSibling;
if (subMenu && subMenu.classList.contains('mega-sub-menu')) {
subMenu.style.display = 'none';
link.setAttribute('aria-expanded', 'false');
link.addEventListener('click', function(event) {
event.preventDefault();
const isExpanded = link.getAttribute('aria-expanded') === 'true';
link.setAttribute('aria-expanded', !isExpanded);
subMenu.style.display = !isExpanded ? 'block' : 'none';
});
}
});
});
</script>
Viewing 1 replies (of 1 total)
Viewing 1 replies (of 1 total)
- You must be logged in to reply to this topic.