Skip to content

Instantly share code, notes, and snippets.

@pagelab
Last active January 25, 2024 16:18
Show Gist options
  • Save pagelab/62062cabeef0e7429b0858506b500726 to your computer and use it in GitHub Desktop.
Save pagelab/62062cabeef0e7429b0858506b500726 to your computer and use it in GitHub Desktop.
Bricks Builder: invert the default behaviour of the dropdown inside the Nav (nestable) element.
<script>
/**
* Nav (nestable) element.
* Invert the default behaviour of the dropdown inside the element.
* Toggles the submenu with two CSS classes (.show-sub-menu and .hide-sub-menu).
*/
// Utility function to add or remove classes from an element.
function toggleClass(element, className) {
if (element.classList.contains(className)) {
element.classList.remove(className);
} else {
element.classList.add(className);
}
}
// Run the function once the window has fully loaded
window.onload = function() {
// Select all elements with the class 'brx-dropdown-content show-sub-menu'
var subMenus = document.querySelectorAll('.brx-dropdown-content');
// Loop through each '.brx-dropdown-content show-sub-menu' element
subMenus.forEach(function(subMenu) {
// Add the 'show-sub-menu' class to each '.brx-dropdown-content show-sub-menu' element
toggleClass(subMenu, 'show-sub-menu');
});
// Select all buttons within elements with the class '.brx-submenu-toggle'
var buttons = document.querySelectorAll('.brxe-dropdown > .brx-submenu-toggle');
// 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 '.brx-dropdown-content show-sub-menu' element that is a sibling of the button
var subMenu = event.target.closest('.brx-dropdown-content') || event.target.closest('.brxe-dropdown > .brx-submenu-toggle').nextElementSibling;
// If the '.brx-dropdown-content show-sub-menu' element exists and matches the '.brx-dropdown-content show-sub-menu' selector
if (subMenu !== null && subMenu.matches('.brx-dropdown-content')) {
// Toggle the 'show-sub-menu' and 'hide-sub-menu' classes on the subMenu element
toggleClass(subMenu, 'show-sub-menu');
toggleClass(subMenu, 'hide-sub-menu');
}
});
});
};
</script>
@pagelab
Copy link
Author

pagelab commented Jan 25, 2024

Don't forget to add the following CSS:

/* Nav (nestable) element: controls the display of the sub-menu in tandem with the corresponding JS code */
/* Note: change the `max-width` value to reflect the Nav element's breakpoint */
@media ( max-width: 768px ) {
    .show-sub-menu {
        display: flex !important;
        opacity: 1;
        visibility: visible;
    }
    .hide-sub-menu {
        display: none !important;
    }
}

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