Search code examples
javascriptjquerycssbootstrap-4sidebar

Sidebar nav - click outside of side nav that closes the sidebar


I am using this sidebar (https://bootsnipp.com/snippets/featured/fancy-sidebar-navigation) and when the user clicks outside of navbar how can I have it close the bar instead of closing via the x.

Here is the JS

$(document).ready(function () {
        var trigger = $('.hamburger');
        var overlay = $('.overlay');
        var wrapperEl = $('#wrapper');
        var isClosed = false;

        function hamburger_cross() {
            if (isClosed === true) {
                overlay.hide();
                trigger.removeClass('is-open').addClass('is-closed');
                isClosed = false;
            } else {
                overlay.show();
                trigger.removeClass('is-closed').addClass('is-open');
                isClosed = true;
            }
        }

        trigger.click(function () {
            hamburger_cross();
        });

        $('[data-toggle="offcanvas"]').click(function () {
            wrapperEl.toggleClass('toggled');
        });
    });

Full working snipped can be found here: https://bootsnipp.com/snippets/featured/fancy-sidebar-navigation


Solution

  • try this Working Fiddle http://jsfiddle.net/ex8ddv5q/811/

    $(document).ready(function () {
      var trigger = $('.hamburger'),
          overlay = $('.overlay'),
         isClosed = false;
    
        trigger.add(overlay).click(function () {
          hamburger_cross(); 
          $('#wrapper').toggleClass('toggled');
        });
    
        function hamburger_cross() {
    
          if (isClosed == true) {          
            overlay.hide();
            trigger.removeClass('is-open');
            trigger.addClass('is-closed');
            isClosed = false;
          } else {   
            overlay.show();
            trigger.removeClass('is-closed');
            trigger.addClass('is-open');
            isClosed = true;
          }
      }
    });