Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialGrace Faires
5,435 Pointsjquery toggle on multiple elements
Hey,
I could really use some help with a menu I've created. I'm trying to create a list of images, that when clicked will reveal text directly underneath, and then hide it when clicked again. I have four images in total. My issue at the moment is that the hidden text has the same class, and so do the images, so when I click one image, all of the hidden text is revealed instead of just the text that corresponds to that one image. Here's an example of the code:
<a href="#"><div class="expander">Click Here</div></a>
<p class="text"> Hidden Text </p>
<a href="#"><div class="expander">Click Here</div></a>
<p class="text"> Hidden Text </p>
<a href="#"><div class="expander">Click Here</div></a>
<p class="text"> Hidden Text </p>
<a href="#"><div class="expander">Click Here</div></a>
<p class="text"> Hidden Text </p>
$(document).ready(function(){
$('.text').hide();
$('.expander').click(function(){
$('.text').slideToggle(200);
});
});
The code works fine on it's own, and my temporary work around at the moment has just been to duplicate it 4 times and then use individual IDs for each image + text respectively, but I know that's not ideal so I wondered how I can achieve the same thing in a smaller amount of code instead of duplicating?
sorry, hope this makes sense! and thank you in advance :)
2 Answers
Christopher Hall
9,052 PointsI think in this case you will need to refer to the clicked element as $(this)
and use tree traversal methods to expand only the hidden text adjacent to it. Try something like this:
$('.expander').click(function(){
// .parent() selects the A tag, .next() selects the P tag
$(this).parent().next().slideToggle(200);
});
If you want to re-hide the other hidden text parts when another one is clicked, then you could add another line of code like this in the anonymous function: $('.text').slideUp(200);
Morgan Waage
11,580 PointsThis is just what I am looking for but I can't get that rehide thing to work. Here is a fiddle showing how I set it up. http://jsfiddle.net/demiurgen/18sep35d/
Grace Faires
5,435 PointsGrace Faires
5,435 Pointsahh, thank you, works perfectly!!