Reputation: 648
I'm working on a Careers page that will show a short preview of a job description along with a toggle, which when clicked, will slide down to show more details of the posting.
The markup looks like this:
<div>
<div class="career-excerpt">
<p>Preview text goes here</p>
</div>
<div class="career-details">
<p>Longer explanation / detail text goes here</p>
</div>
<p><a class="toggle" href="#">Show Details</a></p>
</div>
And here's the jQuery I'm using to toggle open the details section:
$(".career-details").hide();
$(".toggle").click(function () {
$(".career-details").toggle("fast",function() {
$('.toggle').text(
$(this).is(':visible') ? "Hide Details" : "Show Details"
);
});
});
This works to toggle the details open and change the text from "Show Details" to "Hide Details". However, multiple postings will be on each page and with this code, clicking the toggle once will cause all the descriptions to open.
I'd like the toggle to only open the "career-details" div inside the same parent div of the toggle clicked on.
I've tried changing:
$(".career-details").toggle("fast",function() {
to:
$(this).closest(".career-details").toggle("fast",function() {
but after that the toggles don't seem to function at all. Any ideas would be much appreciated, thanks!
Upvotes: 0
Views: 8007
Reputation: 15338
.toggle
is not child of .career-details
so what you did will not work, try this:
$(this).closest("div").find(".career-details").toggle("fast",function() {....});
Upvotes: 6
Reputation: 70159
$(".toggle").click(function() {
var that = $(this); //that == clicked Element
that.parent().prev().toggle("fast", function() {
that.text($(this).is(':visible') ? "Hide Details" : "Show Details");
});
});
If you have more elements between the .toggle
's parent p
and the div
which you're toggling, you can use a more sturdy selector (some performance loss but works the same):
var that = $(this);
that.parent().prevAll('.career-details').first().toggle("fast", function() {
Upvotes: 1
Reputation: 21884
You're almost there, the only problem is how you're trying to find the .career-details
element.
It would be:
$(this).parent().siblings(".career-details").toggle("fast",function() {
Upvotes: 1
Reputation: 50787
$(this).parent().find('.career-details').toggle('fast', function(){
Upvotes: 2