What I’m trying to do is make a multi-level menu. The menu can have as many sub-menus as the user wants. I only want to display the top-most menu to begin with, but after the user clicks on one item, I want the menu to slide down and display that item’s submenu. Then the user can click on one of those items to expand the next submenu and so on and so forth.
So handling the animations for sub-levels was getting kind of sticky after I got to the third submenu. I decided to start over and make a class for my menu to handle the logic. I’m new to JavaScript classes but here is what I have so far:
function Menu(ul, parent){
$ul = $(ul);
this.lis = [];
this.parent = parent || false;
$ul.children('li').each(function(i, li){
this.lis.push(new Li(li, this));
});
}
function Li(li, menu){
$li = $(li);
if($li.children('div').length)
this.submenu = new Menu($($li.children('div')[0]).children('ul')[0], menu);
else
this.submenu = false;
}
var m = new Menu($('#menu'));
The animation I am using for this submenu isn’t the typical slideDown either. I have the menu slide down, and then the submenu fade in. So in my HTML I just wrapped the submenu in a div, slideDown the div, and then fadeIn the ul. So here is what my HTML may look like (Remember there can be any number of items on any level, and any number of levels):
<ul>
<li>
Menu Item 1
<div>
<ul>
<li>
Submenu Item 1
</li>
<li>
Submenu Item 2
<div>
<ul>
<li>Sub-Submenu Item 1</li>
<li>Sub-Submenu Item 2</li>
</ul>
</div>
</li>
<li>
Submenu Item 3
</li>
</ul>
</div>
</li>
<li>Menu Item 2</li>
</ul>
I wanted to write a class that way a <li> item could know where in the Menu it is located. So when I had to close the menu using animations and open another portion, I could just use simple class calls instead of keeping track of the code myself. Obviously I just started writing this code, but I can’t get past this part because I don’t know how.
What happens is Menu Item 1 gets added to this.lis, then Submenu Item 1, but Item 2 won’t get added and I get the error Uncaught TypeError: Cannot call method 'push' of undefined So it seems that since I’m creating new Menu objects, that this gets lost track of. So I don’t know what I can do to make this work. Can somebody please explain it to me?
It took me a little bit to understand the issue, but I believe I have it figured out.
So, you’re correct about the “this” context getting lost. You are almost there as far as keeping things in-line. What you want to do, is pass the “this” context inside of a variable, allowing the next pass-through to use the “this” keyword in it’s context correctly (I hope that makes sense)…
Here, maybe it’s easier to show you:
I haven’t tested this code, but I’m pretty confident it should work for you. Hope it helps!