Reputation: 11
My skills in javascript in jQuery extends only to "cut&paste"-coding, and I would appreciate some help with A) get this simple accordion to work properly B) if possible clean it up a bit. Maybe a class is not needed on each H3 etc.
When clicking any H3 to expand the corresponding div with text, ALL of them are opened. I would of course only want them to open one at a time.
Here is the non-working codepen: http://codepen.io/tuleby/pen/ijqHL
HTML:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<div class="workposts">
<h3 class="toggle-trigger">2014-06-05<span>Heading A</span></h3>
<div class="toggle-content">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud
</p>
</div>
<h3 class="toggle-trigger">2014-06-04<span>Heading B</span></h3>
<div class="toggle-content">
<p>Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
</p>
</div>
<h3 class="toggle-trigger">2014-05-19<span>Heading C</span></h3>
<div class="toggle-content">
<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam
</p>
</div>
<h3 class="toggle-trigger">2014-05-19<span>Heading D</span></h3>
<div class="toggle-content">
<p>Lquis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit </p>
</p>
</div>
</div>
</body>
</html>
jQuery:
jQuery(document).ready(function($) {
$('.workposts').each(function(){
$(this).find('.toggle-content').hide();
});
$('.workposts h3.toggle-trigger').click(function(){
var el = $(this), parent = el.closest('.workposts');
if( el.hasClass('active') )
{
parent.find('.toggle-content').slideToggle();
el.removeClass('active');
}
else
{
parent.find('.toggle-content').slideToggle();
el.addClass('active');
}
return false;
});
});
Upvotes: 1
Views: 476
Reputation: 388316
Your use of the parent element seems to be the problem
jQuery(function ($) {
$('.workposts .toggle-content').hide();
$('.workposts h3.toggle-trigger').click(function () {
var el = $(this);
el.toggleClass('active');
el.next('.toggle-content').slideToggle();
return false;
});
});
Demo: Fiddle
Upvotes: 3
Reputation: 18749
You could just use the Accordion like this...
$(function() {
$( ".workposts" ).accordion();
});
by including the Jquery UI library
<script src="//code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
I updated your CodePen too.
Upvotes: 0