Reputation: 1
I'm trying to create a horizontal clickable menu using jquery for an intranet. Everything works fine until you click on one of the links of the child div - this just makes the whole div disappear again. This is my first attempt so I hope I've explained this ok, I'd really appreciate some help.
script:
$(function(){
$("#nav1").click(function(event) {
event.preventDefault();
$("#teams").slideToggle();
});
$("#teams a").click(function(event) {
event.preventDefault();
$("#teams").slideUp();
});
});
html:
<div id="nav1outer">
<a href="#" id="nav1"> Link 1</a>
<div id="teams">
<ul>
<li><a href="http://child1.com">Child 1</a></li>
<li><a href="http://child2.com">Child 2</a></li>
<li><a href="http://child3.com">Child 3</a></li>
</ul>
</div>
</div>
Many thanks Jayne
Upvotes: 0
Views: 110
Reputation: 1269
What you can do is bind a click event to the document that will hide the dropdown if something outside the dropdown is clicked, but won't hide it if something inside the dropdown is clicked, so your "show" event (or slidedown or whatever shows the dropdown)
$("#nav1").click(function(event) {
$("#teams").slideToggle();
$(document).bind('click', function (e) {
var clicked = $(e.target);
if (!clicked.parents().hasClass("nav1outer")) {
$('#teams').slideUp();
$(document).unbind('click');
}
});
});
The last part is unbind the click event (shown above) so that it can open again
$(document).unbind('click');
Upvotes: 0
Reputation: 4024
I'm assuming your markup actually looks like this
<div id="nav1outer">
<a href="#" id="nav2"> Link 1</A>
<div id="systems">
<ul>
<li><a href="##">Child 1</a></li>
<li><a href="##">Child 2</a></li>
<li><a href="##">Child 3</a></li>
</ul>
</div>
</div>
In your code your telling it to hide/show the systems div when you click on any anchor tag within it.
$(function(){
$("#nav2").click(function(event) { //Click on Nav2 = toggle child div
event.preventDefault();
$("#systems").slideToggle();
});
$("#systems a").click(function(event) { //Click on any child anchor tag = slideup system div
event.preventDefault();
$("#systems").slideUp();
});
});
Look at this fiddle
Upvotes: 1