Reputation: 39
how can i do when i click 'Item' it will open and when click again it will close in Vertical Accordion Menu:
<style>
#nav { float: left; width: 280px; border-top: 1px solid #999; border-right: 1px solid #999; border-left: 1px solid #999; } #nav li a { display: block; padding: 10px 15px; background: #ccc; border-top: 1px solid #eee; border-bottom: 1px solid #999; text-decoration: none; color: #000; } #nav li a:hover, #nav li a.active { background: #999; color: #fff; } #nav li ul { display: none; // used to hide sub-menus } #nav li ul li a { padding: 10px 25px; background: #ececec; border-bottom: 1px dotted #ccc; }
</style>
<ul id="nav">
<li><a href="#">Item 1</a>
<ul>
<li><a href="#">Sub-Item 1 a</a></li>
<li><a href="#">Sub-Item 1 b</a></li>
<li><a href="#">Sub-Item 1 c</a></li>
</ul>
</li>
<li><a href="#">Item 2</a>
<ul>
<li><a href="#">Sub-Item 2 a</a></li>
<li><a href="#">Sub-Item 2 b</a></li>
</ul>
</li>
</ul>
<script type="text/javascript">
$(document).ready(function () {
$('#nav > li > a').click(function(){
if ($(this).attr('class') != 'active'){
$('#nav li ul').slideUp();
$(this).next().slideToggle();
$('#nav li a').removeClass('active');
$(this).addClass('active');
}
});
});
</script>
when i click Item 1,Item 2 it will open sub menus but if i click it again it did not close it.
Upvotes: 1
Views: 1695
Reputation: 988
Didn't work because it didn't run any code on links that already had the active
class.
You can achieve what you want with less code.
$('#nav > li > a').click(function(){
$('#nav > li > a').not(this).removeClass('active').next().slideUp();
$(this).toggleClass('active').next().slideToggle();
});
Upvotes: 1
Reputation: 4211
You need an else
in your jquery to catch the click if the item is already active
$(document).ready(function () {
$('#nav > li > a').click(function(){
if ($(this).attr('class') != 'active'){
$('#nav li ul').slideUp();
$(this).next().slideToggle();
$('#nav li a').removeClass('active');
$(this).addClass('active');
} else {
$('#nav li ul').slideUp();
$('#nav li a').removeClass('active');
}
});
});
#nav li ul {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="nav">
<li><a href="#">Item 1</a>
<ul>
<li><a href="#">Sub-Item 1 a</a></li>
<li><a href="#">Sub-Item 1 b</a></li>
<li><a href="#">Sub-Item 1 c</a></li>
</ul>
</li>
<li><a href="#">Item 2</a>
<ul>
<li><a href="#">Sub-Item 2 a</a></li>
<li><a href="#">Sub-Item 2 b</a></li>
</ul>
</li>
</ul>
Upvotes: 1