Skip to content

Instantly share code, notes, and snippets.

@pagelab
Last active January 25, 2024 16:21
Show Gist options
  • Save pagelab/cb359b31a0b0516e083eb335d518875f to your computer and use it in GitHub Desktop.
Save pagelab/cb359b31a0b0516e083eb335d518875f to your computer and use it in GitHub Desktop.
Bricks Builder: invert the default behaviour of the dropdown inside the Nav element (opened when the menu is clicked).
/* Nav element: change based on the breakpoint for the mobile menu. */
/* Note: change the `max-width` value to reflect the Nav element's breakpoint */
@media ( max-width: 768px ) {
.display-sub-menu {
display: block !important;
}
}
<script>
/**
* Nav element.
* Invert the default behaviour of the dropdown inside the element.
* Toggles the submenu with a single CSS class (.display-sub-menu).
*/
// Run the function once the window has fully loaded
window.onload = function() {
// Select all elements with the class 'sub-menu'
var subMenus = document.querySelectorAll('.sub-menu');
// Loop through each '.sub-menu' element
subMenus.forEach(function(subMenu) {
// Add the 'display-sub-menu' class to each '.sub-menu' element
subMenu.classList.add('display-sub-menu');
});
// Select all buttons within elements with the class '.brx-submenu-toggle'
var buttons = document.querySelectorAll('.bricks-menu-item .brx-submenu-toggle button');
// Loop through each button
buttons.forEach(function(button) {
// Add a 'click' event listener to each button
button.addEventListener('click', function(event) {
// Stop the event from bubbling up the DOM tree
event.stopPropagation();
// Try to select the '.sub-menu' element that is a sibling of the button
var subMenu = event.target.closest('.sub-menu');
// If the '.sub-menu' element exists
if (subMenu !== null) {
// Toggle the 'display-sub-menu' class on the '.sub-menu' element
subMenu.classList.toggle('display-sub-menu');
} else {
// If the '.sub-menu' element does not exist, it means the button has been clicked again
// Find the '.sub-menu' element that is a sibling of the button's closest '.brx-submenu-toggle' ancestor
subMenu = event.target.closest('.brx-submenu-toggle').nextElementSibling;
// If the '.sub-menu' element exists and matches the '.sub-menu' selector
if (subMenu !== null && subMenu.matches('.sub-menu')) {
// Toggle the 'display-sub-menu' class on the '.sub-menu' element
subMenu.classList.toggle('display-sub-menu');
}
}
});
});
};
</script>
@pagelab
Copy link
Author

pagelab commented Jan 25, 2024

Don't forget to add the following CSS:

/* Nav element: change based on the breakpoint for the mobile menu. */
/* Note: change the `max-width` value to reflect the Nav element's breakpoint */
@media ( max-width: 768px ) {
    .display-sub-menu {
        display: block !important;
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment