ilmk ilmk - 4 months ago 100
jQuery Question

Bootstrap left sidebar toggle menu

I got a script for Bootstrap sidebar toggle menu. It works fine for my needs.

Right now the menu is toggling using Toggle Menu button, that is fine.But I need to close the menu if I click, out side of it.

Please check this Fiddle

and help me out. Thanks.

$("#menu-toggle").click(function(e) {
e.preventDefault();
$("#wrapper").toggleClass("toggled");
});

Answer

To get this you have to play with jquery functions like .hasClass, .trigger, .is etc. What i did is, i checked the classes on click and then according to them i wrote this code. Please check

See demo

In detail : First i check the class which is toggling on click of a href so i made a condition that if #wrapperhas toggled class then we will trigger the click event on #menu-toggle but also we have to careful that click should be on body but not the a href of side bar menu that's why i have added another condition with !tag. Hope you will understand and if not then let me know.