HI,
I’m trying to get accordion like functionality without using jQuery’s UI accordion feature.
How can I select the related (child?) div to open when using a link attached to a dt element?
At present my code is
<div id="listings">
<dl class="listings">
<dt>
Get the Milk
</dt>
<dd>
Due Date: 17th Oct
</dd>
<dd>
<a href="#" class="more">more details 2</a>
</dd>
<dd>
<a href="#">mark as complete</a>
</dd>
</dl>
<div class="more_details">
<p>
This is some details about the task that I would to have appear when
the more details 1 link is clicked
</p>
</div>
<dl class="listings">
<dt>
Go to Work
</dt>
<dd>
Due Date: 22th Oct
</dd>
<dd>
Site: None
</dd>
<dd>
<a href="#" class="more">more details 2</a>
</dd>
<dd>
<a href="#">mark as complete</a>
</dd>
</dl>
<div class="more_details">
<p>
This is some details about the task that I would to have appear when
the more details 2 link is clicked
</p>
</div>
</div>
The jQuery I’m using is
$('.more').click(function() {
$('.more_details').slideToggle('fast', function() { });
return false;
});
But the problems I have are
-
When the link with class more is clicked, naturally all the more_details divs open
-
The amount of items in the list will vary as they are being generated from a database query so I cant used fixed, unique class names
Thanks
Jz
The basics are you need to go from
thisand find the element relatively using tree traversal (moving around the DOM from where you clicked). The easiest way looks like this:You can test it out here. This goes from the
.moreyou clicked on up to the.listingselement using.closest()then get’s its.next()sibling (.more_details) and does a.slideToggle()on that (no need for the callback if you’re not doing anything in it).However, a more efficient way to do this once you have more than a few items in your list is to use
.delegate()so there’s just oneclickhandler up on#listings, like this:You can test that version out here.