Reputation: 1930
I am trying to build an accordion by myself using jQuery. This is very simple, but I can't get it right.
This is my HTML
<div id="three">
<dt><a href="#">click one</a></dt>
<dd>content one</dd>
<dt><a href="#">click two</a></dt>
<dd>content two</dd>
<dt><a href="#">click three</a></dt>
<dd>content three</dd>
</div>
This is my script
$('dd').hide();
$('a').on('click', function(){
$(this).parent().next('dd').toggle('slow', function() {
});
$(this).parent().siblings('dd').hide();
})
It will toggle the dd
content when a dt a
is clicked, but I want to close the other opened dd
as well.
Upvotes: 0
Views: 81
Reputation: 8020
HI try like this,
$(function() {
$( "#three" ).accordion();
});
You can use accordion
using Jquery Ui
http://jqueryui.com/accordion/
Upvotes: 0
Reputation: 1592
You can use JQuery UI Accordion
from this link. And use it like:
$(function() {
$("#accordion").accordion();
});
On this structure:
<div id="accordion">
<h3>click one</h3>
<div><p>content one</p></div>
<h3>click two</h3>
<div><p>content two</p></div>
<h3>click three</h3>
<div><p>content three</p></div>
</div>
See example there.
Upvotes: 0
Reputation: 2265
Try with below code.
$('a').on('click', function(){
$(this).parent().parent().find('dd').stop(true,true).slideUp();
$(this).parent().next('dd').stop(true,true).slideDown();
});
Upvotes: 0
Reputation: 816600
I recommend to give the element that holds the according a class so that you can easily find the "root" of the accordion:
<div id="three" class="accordion">
Then you can easily find all dd
elements inside of it and hide all of them but the one that was clicked:
$('a').on('click', function(){
var $dd = $(this).parent().next('dd');
// hide all others
$(this).closest('.accordion').find('dd').not($dd).hide();
$dd.toggle('slow');
});
In general, if you work more with classes than with elements (i.e. .accordion-header
, .accordion-content
, or something like this) and work with "relative" DOM traversal (.closest
) instead of direct traversal ($(this).parent()
), you can make your accordion implementation more flexible.
Upvotes: 1
Reputation: 32581
Hide on click
$('dd').hide();
$('a').on('click', function(){ $(this).parent().next('dd').toggle('slow').siblings('dd').hide('slow');
})
Upvotes: 1
Reputation: 122008
In onclick
you just hide all
before toggling.
$('dd').hide();
$('a').on('click', function(){
$('dd').hide();
$(this).parent().next('dd').toggle('slow', function() {
});
})
Upvotes: 0