Reputation: 71
I'm doing a simple responsive multi-level menu and I'm using toggleclass to open the submenus.
The thing is I want, when I click the menu to open a submenu, if there are any other submenus open, they will close except for the submenu I just opened and to be able to close this submenu by clicking on its menu parent.
I currently use this code:
$(document).ready(function(){
$(".menu > li").click(function(){
$(".submenu.show-menu").toggleClass("show-menu"),
$(this).children(".submenu").toggleClass("show-menu")
;
});
});
JSFiddle: https://jsfiddle.net/g7d3wmnc/ Try opening a submenu by clicking a menu. Then click an other menu to open its submenu. See how the previous submenu you opened closes. That is working right. Now try to close the submenu you just opened by clicking on its menu. You'll see it doesn't work. That's the problem.
The problem with this code, is that if I open one submenu and then an other submenu, the previous submenu I opened will close. That works. BUT then I can't close the submenu I just opened unless I open an other submenu and so on.
I pressume it is because of this line:
$(".submenu.show-menu").toggleClass("show-menu"),
This code will see the current submenu I have opened has the class show-menu and will proceed to toggle the class off and as the submenu no longer has that class, the next line of code will proceed to toggle the class on, as it should.
So, how do I prevent this from happening? I thought if I could exclude the submenu of the menu I'm clicking of the first line of code then it would work as I want it to, but I don't know how to do that. I'm quite new to Jquery.
I have tried:
$(".submenu.show-menu").not(this).toggleClass("show-menu")
$(".submenu.show-menu").not(this).children(".submenu").toggleClass("show-menu")
This is the website I'm trying this on: http://etrostruewowdesigncomplete2.esy.es/phpBB3/index.php?sid=2ae138c61784f734c9d98c0944359e42
You can only see the responsive menu if the window's size is below 999px and you'll have to click/tap on the magnifying glass to open it (the theme is still not finished)
Upvotes: 0
Views: 429
Reputation: 1565
In the code you are using
$(".submenu.show-menu").not(this).toggleClass("show-menu");
To select elements showMenu other than the active one. Which is wrong as this in this context reffers to the span element. Here is a working demo.
https://jsfiddle.net/8fx2u56w/
But i guess you are hoping for a solution like https://jsfiddle.net/6Lu8ajp2/
Upvotes: 1
Reputation: 641
there.
This snippet should work for you better:
$(document).ready(function(){
$(".menu > li").click(function(){
$(".submenu").removeClass("show-menu");
$(this).children(".submenu").toggleClass("show-menu");
;
});
});
Upvotes: 0