Close drop down menu when clicking outside menu

I have the following

function subNavToggle() {
    var subNav = document.getElementById("subnav-section");
    if (subNav.className === "navigation-subnav") {
        subNav.className += " responsive";
    } else {
        subNav.className = "navigation-subnav";
    }
 }

I am trying to get the expanded menu to close when clicking outside of menu.

I have this, which will close the menu, but it also closes the hamburger menu – preventing the user to be able to open again.

 $(document).click(function(event) { 
     var $target = $(event.target);
     if(!$target.closest('.sub_nav_links').length && 
     $('.sub_nav_links').is(":visible")) {
       $('.sub_nav_links').hide();
     }        
   });

Also thought I could get away with the following, but it actually does the opposite. Opening outside menu item.

window.onclick = subNav;

Answer

  $('html').on('click, touchend', function (e) {
    // Close hamburger menu when tapping outside
    if ($(e.target).closest('#subnav-section').length == 0) {
        var opened = $('.navigation-subnav').hasClass('responsive');
        if (opened === true) {
            $('.navigation-subnav').collapse('hide');
        }
    }
});