The way this is usually handled is by registering a click event on the body and checking if you’ve clicked on something outside of the menu. This works because all events propagate up the DOM to the root node <html> unless they’re explicitly stopped.
var $body = $('body');
$body.on('click', function(event) {
var clickedOutside = $(event.target).closest('.menu-toggle').length == 0;
if (clickedOutside && $body.hasClass('menu-open')) {
$body.removeClass('menu-open');
}
})
I disagree, the only thing I’d suggest changing in the original code is to use ‘on’ rather than bind for events, that’s the recommended method to use.
Yes, it’s possible to move this outside of the HTML. It’s not too bad inline here but generally it’s great advice to keep your JS out of the HTML entirely.
One thing that’s happened though. When I click on the nav bar or outside the nav bar, it closes it. I just want it to close if it’s clicked outside the nav bar, not inside as well. Any ideas? Thank you again!