Explain Codes LogoExplain Codes Logo

Hide Twitter Bootstrap nav collapse on click

html
bootstrap
responsive
event-delegation
Alex KataevbyAlex Kataev·Aug 18, 2024
TLDR

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:

$('.navbar-nav').on('click', 'li a', () => $('.navbar-collapse').collapse('hide'));

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:

<a href="#section" data-toggle="collapse" data-target=".navbar-collapse.show">Link</a>

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:

$('.navbar-nav a').click(function(event) { // Only scroll to a section for non-collapse toggles if ($(this).attr('data-toggle') !== 'collapse') { $('html, body').animate({ // Like a boss, straight to the section scrollTop: $($(this).attr('href')).offset().top }, 500); } // Collapse! Like Cardi B's gloves 😎 $('.navbar-collapse').collapse('hide'); });

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:

// For Bootstrap 3 $('.navbar-nav').on('click', 'li a', () => $('.navbar-collapse.in').collapse('hide')); // For Bootstrap 4 $('.navbar-nav').on('click', 'li a', () => $('.navbar-collapse.show').collapse('hide'));

Addressing edge cases

Checking before collapsing

Before collapsing the navbar, validate if it is actually expanded. This step mitigates unnecessary DOM manipulations:

$('.nav a').on('click', function() { if($('.navbar-toggle').css('display') != 'none'){ // If clicked and expanded, behave like a Domino's Pizza box. Collapse! 😄 $(".navbar-toggle").trigger("click"); } });

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.

$(document).on('click', '.navbar-nav li a', function() { // Hide, lest Jon Snow finds you... (GoT Fans will get it) 😄 $('.navbar-collapse').collapse('hide'); });

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.