Home > Blockchain >  How to close navbar when clicking outside of it
How to close navbar when clicking outside of it

Time:11-16

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?

JSFiddle: https://jsfiddle.net/v45q3ykh/6/

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

CodePudding user response:

$(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.

CodePudding user response:

$(document).on('click', function (event) {
    if ($(event.target).closest('.main-nav').length === 0) {
        // Close button code
    }
});
  • Related