Search code examples
javascriptbootstrap-4navbar

Adding code to existing .js to collapse navbar when click outside menu


Currently I use .js for my sticky navbar in Bootstrap 4.1.3 which works as desired. I have tried to insert a function in the script, which makes the navbar bar collapse on mobile phones if you click outside the menu. However, without luck. https://biogenity.com/RC19/index.html

The code I am currently using is:

        $(document).ready(function () {
            var stickyToggle = function (sticky, stickyWrapper, scrollElement) {
                var stickyHeight = sticky.outerHeight();
                var stickyTop = stickyWrapper.offset().top;
                if (scrollElement.scrollTop() >= stickyTop) {
                    stickyWrapper.height(stickyHeight);
                    sticky.addClass("is-sticky");
                }
                else {
                    sticky.removeClass("is-sticky");
                    stickyWrapper.height('auto');
                }
            };

            $('[data-toggle="sticky-onscroll"]').each(function () {
                var sticky = $(this);
                var stickyWrapper = $('<div>').addClass('sticky-wrapper'); 
                sticky.before(stickyWrapper);
                sticky.addClass('sticky');

                $(window).on('scroll.sticky-onscroll resize.sticky-onscroll', function () {
                    stickyToggle(sticky, stickyWrapper, $(this));
                });

                stickyToggle(sticky, stickyWrapper, $(window));
            });             
        });

I want to be able to implement a similar function as the following. It is not certain that this is the best solution for "collapse when you click outside the menu".

        $(document).on('click', function(event){
          var $clickedOn = $(event.target),
              $collapsableItems = $('.collapse'),
              isToggleButton = ($clickedOn.closest('.navbar-toggle').length == 1),
              isLink = ($clickedOn.closest('a').length == 1),
              isOutsideNavbar = ($clickedOn.parents('.navbar').length == 0);

          if( (!isToggleButton && isLink) || isOutsideNavbar ) {
            $collapsableItems.each(function(){
              $(this).collapse('hide');
            });
          }
        });

Thanks in advance.


Solution

  • Based on your code, try this:

    $(document).click(function (event) {
      var clickedOn = $(event.target),
        isNavbar = clickedOn.hasClass('navbar'),
        // Target only nav links not all links
        isNavbarLink = clickedOn.closest('.nav-link').length == 1,
        navbarCollapse = $('.navbar-collapse'),
        isNavbarOpen = navbarCollapse.hasClass('show');
    
      // if its not navbar and navbar is opened
      if (!isNavbar && isNavbarOpen) {
        // if the user is not cliking on the nav links
        if (!isNavbarLink) {
          // thes close the navbar 
          navbarCollapse.collapse('hide');
        }
      }
    });