Reputation: 100
I have managed to write a simple script for a drop down menu but I am having issues making it so that only the section under the menu item that is clicked drops down in stead of all of the sub menus. I have a Jsfiddle.
<ul id="nav">
<li class="parent"><a class="nav-top" href="#">Web Design</a>
<ul class="sub-nav">
<li><a class="nav-top" href="#">Self Storage Websites</a></li>
<li><a class="nav-top" href="#">Responsive Websites</a></li>
</ul>
</li>
<li class="parent"><a class="nav-top" href="#">Internet Marketing</a>
<ul class="sub-nav">
<li><a class="nav-top" href="#">Real SEO</a></li>
<li><a class="nav-top" href="#">PPC (Pay Per Click) Ads</a></li>
<li><a class="nav-top" href="#">Social Media Marketing</a></li>
</ul>
</li>
<li class="parent"><a class="nav-top" href="hosting.html">Website Hosting</a></li>
<li class="parent"><a class="nav-top" href="#">About Us</a>
<ul class="sub-nav">
<li><a class="nav-top" href="#">About EiD</a></li>
<li><a class="nav-top" href="#">Careers</a></li>
</ul>
</li>
<li class="parent"><a class="nav-top" href="hosting.html">Contact Us</a></li>
$(document).ready(function() {
$('.parent').click(function() {
$('.sub-nav').toggleClass('visible');
});
});
#nav li {
padding: 0;
line-height: 48px;
width: 100%;
text-align: center;
/*text-transform: uppercase;*/
font-weight: 400;
color: #fff;
white-space: nowrap;
}
.sub-nav {
background: #e2e;
display: block;
overflow: hidden;
}
#nav ul.sub-nav {
display: none;
}
#nav ul.visible {
display: block;
}
Any info would be greatly appreciated. Thanks!
Upvotes: 0
Views: 45
Reputation: 26143
It's a straight-forward fix. You're selecting all .sub-nav
, instead of just the the relevant one. Try this...
$(document).ready(function() {
$('.parent').click(function() {
$(this).find('.sub-nav').toggleClass('visible');
});
});
If you want to toggle the clicked one, as well as close any other open ones then you'll need a little more...
$(document).ready(function() {
$('.parent').click(function() {
$(".parent").not(this).find(".sub-nav").removeClass("visible");
$(this).find('.sub-nav').toggleClass('visible');
});
});
Upvotes: 1
Reputation: 165
$(document).ready(function() {
$('.parent').click(function() {
$('.sub-nav', this).toggleClass('visible');
});
});
Upvotes: 1