Reputation: 37
I am trying to create an accordion effect with a nested unordered list.
<script>
$(document).ready(function(){
$('a').click(function(){
$('.open').toggle();
active = $(this).next().toggle();
active.addClass('open');
});
});
</script>
With the above code I know that it closes everything with a class of "open", and I know why, but I wish to add code to skip over the element indicated in the variable "active".
Here's my full code if that helps:
<style>
ul {
display:none;
}
</style>
<script>
$(document).ready(function(){
$('a').click(function(){
$('.open').toggle();
active = $(this).next().toggle();
active.addClass('open');
});
});
</script>
<a href="#" id="toggle">toggle menu</a>
<ul id="menu">
<li>
<a href="#">cool 1</a>
<ul>
<li><a href="#">cool 1</a>
<ul>
<li>hey 1</li>
<li>hey 2</li>
</ul>
</li>
<li><a href="#">cool 2</a>
<ul>
<li>hey 1</li>
<li>hey 2</li>
</ul>
</li>
<li><a href="#">cool 3</a></li>
</ul>
</li>
<li><a href="#">cool 2</a></li>
<li>
<a href="#">cool 3</a>
<ul>
<li><a href="#">cool 1</a>
<ul>
<li>hey 1</li>
<li>hey 2</li>
</ul>
</li>
<li><a href="#">cool 2</a></li>
<li><a href="#">cool 3</a></li>
</ul>
</li>
</ul>
Upvotes: 1
Views: 214
Reputation: 1598
To keep the code short-and-sweet. I'll assume that you want the sub items to remember their state.
Secondly, I'll throw in a bonus tip that you should use a delegated handler. This will help code maintenance if you decide to add menus dynamically. i put it on body
here, but you probably want to define / use some kind of wrapping div
or equivalent
$('body').on('click','a', function(){
$(this).siblings('ul').toggleClass('open');
});
Upvotes: 0
Reputation: 123739
You can use .toggleClass().
$(document).ready(function(){
$('a').click(function(){
var $this = $(this);
var $ul = $this.next().toggle().toggleClass('open');
$('.open').not($this.parents().add($ul)).hide()
});
});
Upvotes: 1
Reputation: 388316
Try
$(document).ready(function(){
$('a').click(function(){
var $this = $(this);
var $ul = $this.next().toggle().addClass('open');
$('.open').not($this.parents().add($ul)).hide().removeClass('open')
});
});
Demo: Fiddle
Upvotes: 1