Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

152
Views
How to close navbar when clicking outside of it

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');
  });
});
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

$(document).on('click', function (event) {
    if ($(event.target).closest('.main-nav').length === 0) {
        // Close button code
    }
});
about 4 years ago · Juan Pablo Isaza Report

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!