Reputation: 71
I'm trying to create some sort of "spoiler" for a forum. It's pretty simple, though i'm fairly new to jquery. But now i got this problem when placing a toggle div element inside another toggle div element, the 2nd toggle doesn't work. Can anyone point me in the right direction?
Jquery
$(document).ready(function(){
$('.head').click(function() {
$('.body').toggle('slow')
});
});
HTML
<div class="head">
Show Content
</div>
<!--1st toggle div-->
<div class="body" style="display:none;">
Content
<div class="head">
Show Content
</div>
<!--2nd toggle div-->
<div class="body" style="display:none;">
Content
</div>
</div>
Thanks to everyone that's trying to help :)
EDIT:
Right after i posted i've seen that i was using multiple ID's in the HTML code. I've changed the div id's to classes, but now when i click to show content1, content2 also shows up. Can someone help me with it?
Upvotes: 2
Views: 2219
Reputation: 50767
You need to separate it by classes, and then use some nice jQuery Traversal methods to make it cleaner.
We'll use the .next selector, here's a live jsFiddle.
Here's the code I've used to make it work; change head and body to classes instead of ID's.
$(document).ready(function(){
$('.head').click(function() {
$(this).next('.body').toggle('slow')
});
});
Upvotes: 1
Reputation: 1777
Yeah try this https://jsfiddle.net/ufC5B/2/
$(document).ready(function(){
$('.head').click(function() {
$(this).siblings('.body:first').toggle('slow')
});
});
Upvotes: 1
Reputation: 412
Both divs show up because $('.body')
will match all elements in the DOM that have a class of body
and perform the function on ALL of them.
To avoid that, use specifically named divs or add another identifier to the elements, like the example below.
<div class="head" data-depth="1">
Show Content 1
</div>
<!--1st toggle div-->
<div class="body" data-depth="1" style="display:none;">
Content
<div class="head" data-depth="2">
Show Content 2
</div>
<!--2nd toggle div-->
<div class="body" data-depth="2" style="display:none;">
Content
</div>
</div>
$(document).ready(function(){
$('.head').click(function() {
var depth = $(this).attr('data-depth');
$('.body[data-depth=' + depth + ']').toggle('slow');
});
});
Upvotes: 2