Topic: How to prevent (mega) dropdown menu from closing on background click?
Alanc free asked 3 years ago
Expected behavior: I would like to have my mega dropdown menu only open and close using the link in my navigation bar (.nav .nav-item .nav-link)
Actual behavior Clicking ANYWHERE within the opened mega menu closes it again. It is impossible to navigate through a carousel or interact with other elements that are not a hard link to another page, as the menu just closes again.
Some sources say something about stopPropagation(); but I have not been able to adapt that to my case and make it work.
Resources (screenshots, code snippets etc.) The mega menu code is based off of the snippet provided by MDB.
To keep other events possible you need to check if the event of clicking happened on the desired element and if so then stop propagation.
I created a simple solution to this: https://mdbootstrap.com/snippets/jquery/pjoter-2-0/1276039
I left the console logs for you to check what each important element of code stands for. You can modify the if statement by picking any condition you want. Please understand that e.target returns the direct 'clicked' element. You need to check if this element is exactly the one you want to stop the event from happening. If you want to narrow down the elements clicked you can pick children of the container or even directly select elements inside of the megamenu to stop their propagation.
If you need additional help I am here for you.
Best Regards, Piotr
To stop even from occurring on any given jQuery object you can create similar event handler to this one demonstrated in snippet bellow. This is a simple example that should help you with your development needs. https://mdbootstrap.com/snippets/jquery/pjoter-2-0/1276039
If you need any help I am here for you.
Best Regards, Piotr
It's based off of the Mega menu dark version but has been customized a little. Here's a snippet of my nav menu: https://mdbootstrap.com/snippets/jquery/alanc/1267036
Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.
- User: Free
- Premium support: No
- Technology: MDB jQuery
- MDB Version: 4.8.7
- Device: Laptop
- Browser: Brave
- OS: Windows 10 64-bit Pro
- Provided sample code: No
- Provided link: No