I'm trying to get a jquery slide menu working, but I'm out of ideas right now. How can I stop the menu collapsing when clking on a submenu entry?
Here's what I've got so far - js-part, navigation code, and finally the css part that is relevant:
<script type="text/javascript">
$(document).ready(function() {
$('ul .sub').hide();
$("li:has(.sub)").click(function() {
$("ul", this).toggle('slow');
});
</script>
<nav id="nav" class="nav">
<ul>
<li class="current"><a href="#a">menu1</a></li>
<li><a href="#b">menu2</a>
<ul class="sub">
<li><a href="#ba">sub2a</a></li>
<li><a href="#bb">sub2b</a></li>
<li><a href="#bc">sub2c</a></li>
</ul>
</li>
<li><a href="#c">menu3</a></li>
<li><a href="#d">menu4</a>
<ul class="sub">
<li><a href="#da">sub4a/a></li>
<li><a href="#db">sub4b</a></li>
</ul>
</li>
</ul>
</nav>
And here's the css:
.nav li {
list-style:none;
line-height: 30px;
}
.nav a:link, .nav a:visited{
color:#333 !important;
text-decoration:none;
}
.nav a:hover {
color:#9bb710;
text-decoration:none;
}
.current a:link, .current a:hover, .current a:visited {
color:#9bb710 !important;
}
.sub {
color:#333 !important;
text-decoration:none;
font-size: 14px;
margin-left: 15px;
line-height: 22px;
}
This is happening due to event propagation: when you click on a subitem, "click" event is propagated up to the container "li".
You can prevent this by adding:
$("li").click(function(event) {
event.stopPropagation();
});
Here's a jsfiddle example: http://jsfiddle.net/EWXPy/