How to Close a Toggle Menu with an Outside Click

By Zedric Myers | Published August 20, 2018 | Categories: Web Development

Adding a toggle menu is nice and straight forward with your preference of CSS or jQuery, but when you want to be able to click outside of the menu and close you will need to add a little more jQuery functionality.

This option adds a few extra lines of jQuery, but overall very simple way to close the menu when clicking outside the menu button area or the expanded menu, itself.

Please note, in this example we use specific areas instead of on “document” click. It can cause issues in certain browsers, depending on the options setup for the toggle menu. The example assumes you already have the toggle menu in place.

jQuery Example:

jQuery("#menu-button").on("click", function (event) {
    jQuery(this).toggleClass('on');
    event.stopPropagation();
});
jQuery(".sub-menu").on("click", function (event) {
    event.stopPropagation();
});
jQuery(".footer, .main-content").on("click", function () {
    jQuery('#menu-button').prop('checked', true); //method of choice: our method uses the input checkbox method as fallback.
    jQuery('#menu-button').removeClass('on');
});

Contact Us To Find Out More

Have questions? Need help? Contact us and we'll be in touch soon!

* Required

Beacon
164 Thatcher Road
Greensboro, NC 27409
Map and Directions

Sales & Marketing
336.232.5687