How to close navbar when clicking outside of it

Issue

How can I edit my code so that the navbar closes when clicked outside of it but remain open if something inside of it is clicked?

$(document).ready(function() {
  $('.nav-btn').on('click', function() {
  $('.nav-btn').removeClass('active');
    $(this).parent().find('.sub-menu').slideToggle();
    $(this).toggleClass('active');
  });
});

Solution

$(document).ready(function () {
    $('.nav-btn').on('click', function (e) {
        
        // Stop Document to be clicked when clicked in nav.
        e.stopPropagation()

        $('.nav-btn').removeClass('active');
        var subMenu = $(this).parent().find('.sub-menu')
        if (!$(".sub-menu").is(":visible")) {
            $(this).parent().find('.sub-menu').slideToggle();
        }
        $(this).toggleClass('active');
    });

    // Toggle Sub Menu and remove active when Any vacant place is clicked
    $(this).on('click', function (event) {
        $('.nav-btn').removeClass('active');
        $('.nav-btn').parent().find('.sub-menu').slideToggle();
    });

    // Prevent View close when Sub Items is clicked
    $('.sub-menu').on('click', function (e) {
        e.stopPropagation()
    })
});

Hi, You just need to prevent the document click when clicked on the nav item and handle some additional things as done in the above code.

You can see Plunker example here also.

Answered By – Anuj Raghuvanshi

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published