Reputation: 428
I'm reasonably new to JQuery, and I'm muddling through a bit, but by my logic the below should work. can you point out what's wrong?
I've got a bunch of repeating content blocks with classnames .acc-0, acc-1 and so on, which should hide and show .plans-breakdown
when you click on .open-link
button which sits inside the block(s)
This is the example with .acc-1
$('.acc-1').each(function(){
$(this).find('.open-link').on('click',function() {
$('.plans-breakdown').not(this).css('display','none');
$(this).find('.plans-breakdown').fadeToggle(600);
});
});
HTML;
<div class="schedule-plan acc-0">
<div class="open-link">Floor plan acc-0</div>
<div class="plans-breakdown">
content here
</div>
</div>
</div>
<div class="schedule-plan acc-1">
<div class="open-link">Floor plan acc-1</div>
<div class="plans-breakdown">
content for acc-1 here
</div>
</div>
I want this function to only work on the specific code block. In this example .acc-1
. So I've wrapped the function in a $('.acc-1').each(function(){}
I've used (this)
to specify the correct .open-link
button which needs to trigger the function. Also, on the .fadeToggle
action, to target the instance of .plan-breakdown
which is nested inside .acc-1
Check out my fiddle, notice how the first block works (.acc-0). When I use .each
it doesn't.
http://jsfiddle.net/bazzle/Q4zmS/2/
Thanks,
Upvotes: 2
Views: 51
Reputation: 71140
You can simply use:
// for every element with a acc- class...
$('[class*=acc-]').on('click', function () {
// hide all elements previously shown
$('.plans-breakdown').css('display', 'none');
// fade in the child element
$(this).find('.plans-breakdown').fadeToggle(600);
// for all active links, remove the active class
$('.open-link').removeClass('active');
// add the active class to the child link
$(this).find('.open-link').addClass('active');
});
I'd also add:
.plans-breakdown{
display:none;
}
To your CSS, removing the need for the JS:
$('.plans-breakdown').css('display', 'none');
And change your CSS to the below as you have nested rules, which is invalid:
.schedule-plan {
display:block;
padding-top:.3em;
cursor:pointer;
}
.active {
color:black;
}
.plans-breakdown {
margin:1em 0 2em 0;
cursor:default;
}
.plans-breakdown {
display:none;
}
Upvotes: 2