1

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');
  });
});
  • Try this https://stackoverflow.com/questions/152975/how-do-i-detect-a-click-outside-an-element – MaReAL Nov 15 '21 at 19:28

3 Answers3

0
$(document).on('click', function (event) {
    if ($(event.target).closest('.main-nav').length === 0) {
        // Close button code
    }
});
Steve
  • 76
  • 3
  • 3
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 15 '21 at 19:16
0
$(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.

Anuj Raghuvanshi
  • 664
  • 1
  • 7
  • 24
0

Another possible way is by wrapping all the content inside another div (except the header & navbar) and using the onclick tag:

<div onclick="hideNavbar()">
     all your content goes here
</div>

function hideNavbar() {
   $('.navbar-collapse').collapse('hide');
   // getting the navbar div with jQuery  
  // and calling the function 'hide' of the Bootstrap class 'collapse'
}
TerryMars
  • 27
  • 4