Reputation: 13
I'm currently trying things with jQuery for a mobile website. I implemented a very simple slide-in menu I found here: http://jsfiddle.net/jm36a13s/
Now I'm trying to get it to close when clicking anywhere but the menu. I tried a few suggestions I found already but for some reason I can't get it to work.
Thanks in advance!
$(document).ready(function() {
$menuLeft = $('.pushmenu-left');
$nav_list = $('#nav_list');
$nav_list.click(function() {
$(this).toggleClass('active');
$('.pushmenu-push').toggleClass('pushmenu-push-toright');
$menuLeft.toggleClass('pushmenu-open');
});
});
Upvotes: 0
Views: 166
Reputation: 36794
You can remove your classes when the user clicks anywhere in the window.
Then you can stop the event bubbling up the DOM tree when either $pushMenu
or $nav_list
is clicked, to prevent the above:
$(document).ready(function () {
var $menuLeft = $('.pushmenu-left'),
$nav_list = $('#nav_list'),
$pushMenu = $('.pushmenu-push');
$nav_list.click(function () {
$(this).toggleClass('active');
$pushMenu.toggleClass('pushmenu-push-toright');
$menuLeft.toggleClass('pushmenu-open');
}).add($menuLeft).click(function (e) {
e.stopPropagation();
});
$(window).click(function () {
$nav_list.removeClass('active');
$pushMenu.removeClass('pushmenu-push-toright');
$menuLeft.removeClass('pushmenu-open');
});
});
Upvotes: 2
Reputation: 8868
You may also try the following. The whole idea is to register a click event on the entire document and hide the menu if the target_id
is not "nav_list"
$(document).click(function(e)
{
if(e.target.id != "nav_list")
{
$nav_list.removeClass('active');
$pushMenu.removeClass('pushmenu-push-toright');
$menuLeft.removeClass('pushmenu-open');
}
});
http://jsfiddle.net/jm36a13s/23/
Upvotes: 0