0

I am trying to get a jumbo slide in navigation to close when the user clicks outside of the navigation.

I currently have a click event set on a hamburger icon which toggles a class on the navigation. This class uses CSS to reposition the navigation (As well as adds a class to the body tag). The navigation covers around 75% of the screen width. However, I would like the user to be able to close the menu when they click outside this menu and not just the hamburger icon. I currently have the following

$('.c-primary-nav-toggle').on('click', function() {
    $(this).toggleClass('open'); /* used to change the style of the hamburger */
    $('.off-canvas-nav').toggleClass('menu-in'); /* used to bring the nav into view */
});

$(document).on('click',function(){
    $('body').hasClass('mobile-menu-open').find('.off-canvas-nav').removeClass('menu-in');
});

/* Adds class to the body when hamburger is click in order to remove scroll bar from body */
$('body').removeClass('mobile-menu-open');
    $(".c-primary-nav-toggle").on('click',function() {
    $('body').toggleClass('mobile-menu-open');
});

<body>
    <div class="c-primary-nav-toggle"></div>
    <div class="off-canvas-nav">
        NAVIGATION
    </div>
</body>
Al-76
  • 1,738
  • 6
  • 22
  • 40
  • Please include all relevant code. – Carsten Løvbo Andersen Sep 03 '20 at 13:01
  • one way to achieve this is adding a blank div with absolute/fixed positioning over the entire document, z-index just above all other content but below the menu you wish to close when clicking outside, and then add jquery onclick of that div to remove the navbar and background div all together – Ramon de Vries Sep 03 '20 at 13:03
  • This one can help you: https://stackoverflow.com/questions/152975/how-do-i-detect-a-click-outside-an-element – sssurii Sep 03 '20 at 13:07
  • @sssurii Thank you. I am a bit closer thanks to you sharing that other answer. – Al-76 Sep 03 '20 at 13:14
  • Could you not just add an onblur event to the navigation and then when they click away it fires and then act accordingly within the event code. – mkane Sep 03 '20 at 14:23

0 Answers0