Hide Twitter Bootstrap nav collapse on click
Looking for a code snippet to close the Bootstrap navbar whenever a menu item is clicked? Here's how to achieve it by attaching a click event to nav links:
The click event applies to all a
elements within .navbar-nav
. Invoking .collapse('hide')
on the .navbar-collapse
class when a link is clicked ensures a tidy, user-friendly navigation.
Adapting to different Bootstrap versions
Different versions of Bootstrap, specifically, Bootstrap 3 and Bootstrap 4, handle the collapse component differently. So, ensure to check out the collapse.js documentation specific to your Bootstrap version.
Bootstrap's data-toggle & data-target
Sometimes you can achieve the desired behavior without writing additional scripts. Bootstrap provides data-toggle
and data-target
attributes directly in HTML navigation links:
This results in a no-JavaScript solution and automatically takes advantage of Bootstrap's built-in functionality.
Keeping navigation smooth
Ensure to maintain the natural scroll of one-page templates while implementing the collapse feature. On smooth scrolling, you want the collapse to hide without interrupting the scroll functionality. Here's how:
Compatibility matters
Don't let your solution turn into "Mission Impossible" for different Bootstrap versions. Adjust the jQuery selectors based on the classes used in different versions:
Addressing edge cases
Checking before collapsing
Before collapsing the navbar, validate if it is actually expanded. This step mitigates unnecessary DOM manipulations:
Behaving responsive
Demand your solution to cater to different screen sizes given the responsive features of Bootstrap. Your click events should identify the collapsed state, which is likely on smaller devices.
More Advanced interactions and troubleshooting
Getting acquainted with event delegation
Get to know event delegation - quite the potential lifesaver for dynamic pages where nav links might be added or removed post DOM-ready.
Dealing with dynamic content loading
When working with platforms that load content dynamically (e.g., Angular or React), always reinstating event handlers after each DOM update is crucial. Look into lifecycle hooks or useEffect to bind the collapse logic post-components rendering.
Prioritising Accessibility
Your solution should neither disturb accessibility nor default browser behavior such as focus management. When testing, ensure all navigation is achievable via keyboards and screen-readers alone too.
Was this article helpful?