The function below acts as an slidetoggle accordion (for a list of WordPress posts) and it does a number of things, like toggle, add active classes and “declick” the open toggle div. Worked fine with the three divs – .entry-post, .entry-title and .entry-content – until… wait for it… I needed to add another div in the markup.
The other div I needed to add is for the publication date, and with that fourth div, the accordion action breaks, because the function operates in determining the next div.
How can I get this function to take into account and ignore thedate div I had to add in the markup? (I can’t change the div to a span.)
JSfiddle here: http://jsfiddle.net/WnpGv/53/
Function:
$(".entry-title").click(function() {
$this = $(this);
$content = $this.next(".entry-content");
if (! $this.is('.active-title')) {
$('.active-title').removeClass('active-title');
$this.addClass('active-title');
$(".entry-content:visible").slideToggle(400);
$content.slideToggle(400);
}
});
Basic markup:
<div class="entry-post">
<h2 class="entry-title">Post Title 1</h2>
<div class="thedate">(publication date)</div> <!--this is the div I added -->
<div class="entry-content">Lorem Ipsum Lorem Ipsum</div></div>
You can’t change
next(), it always looks at the next sibling element:[emphasis mine.]
You could, however, use
parent()andfind():JS Fiddle.
Edited to use
closest('.entry-post')in place ofparent('.entry-post'):JS Fiddle.
References:
next()parent()closest()find()