The purpose of this element is to have a collapsible navigation system based entirely from a simple unordered list. By default all nested lists will be hidden, and .toggle divs (buttons) attached to li items that contain a nested list. These .toggle divs should then hide/show the nested list as well as apply a class to the toggle button.
I’ve tested this code by manually inserting the .toggle div (location noted with [toggle div]), and everything works perfectly. When it’s added through append() though, nothing seems to work. Does anyone know what might be causing this problem? Any help would be greatly appreciated – thanks!
HTML:
<div id="nav">
<ul>
<li><a href="#">nav item</a>[toggle div]
<ul>
<li><a href="#">nav item</a></li>
<li><a href="#">nav item</a></li>
<li><a href="#">nav item</a>[toggle div]
<ul>
<li><a href="#">nav item</a></li>
<li><a href="#">nav item</a></li>
<li><a href="#">nav item</a></li>
</ul>
</li>
<li><a href="#">nav item</a></li>
</ul>
</li>
<li><a href="#">nav item</a></li>
<li><a href="#">nav item</a></li>
<li><a href="#">nav item</a></li>
</ul>
</div>
jQuery:
$(function(){
$("#nav ul li").has("ul").append("<div class='toggle'></div>");
$(".toggle").live("click", function() {
if($(this).next().is(":hidden")) {
$(this).next().show();
$(this).addClass("toggled");
} else {
$(this).next().hide();
$(this).removeClass("toggled");
}
});
});
Try this:
If will select all
<ul>elements which are directly nested in<li>elements, and adds the<div>in front of each of them.Have a look at the demo: http://jsfiddle.net/xXRSZ/1/