Reputation: 6361
I have a piece of code here that is repeated multiple times in a single html file.
<div class="message">
<label id="slideDown"> Read </label>
<p id="messageBody" class="hidden"> Body </p>
</div>
<div class="message">
<label id="slideDown"> Read </label>
<p id="messageBody" class="hidden"> Body </p>
</div>
jQuery used to slide down messageBody.
$('#slideDown').click(function() {
$('#messageBody').slideToggle('slow');
});
My questions is how can I get it so that when I click on the label Read for one message, it only slides down the messageBody that is within its div?
Upvotes: 1
Views: 230
Reputation: 2294
Based on the HTML structure in your jsFiddle (see comment reply to magzalez's answer), the following should work. This requires no changes in case you add more messages later.
HTML:
<div class="message">
<h2 class="messageSubject">Subject<label class="slideDown"> Read </label></h2>
<label class="messageSender"> Sender </label>
<div class="bodyWrapper">
<p class="messageBody hidden"> Body </p>
</div>
</div>
<div class="message">
<h2 class="messageSubject">Subject<label class="slideDown"> Read </label></h2>
<label class="messageSender"> Sender </label>
<div class="bodyWrapper">
<p class="messageBody hidden"> Body </p>
</div>
</div>
CSS:
.hidden {
display: none;
}
JavaScript:
$('.slideDown').click(function() {
$(this).closest(".message").find('.messageBody').slideToggle('slow');
});
Here is a jsFiddle to test (click Run): http://jsfiddle.net/willslab/7ytZR/2/
Upvotes: 1
Reputation: 1406
You can fix and have less code if you change the IDs to classes like this:
HTML
<div class="message">
<label class="slideDown"> Read </label>
<p class="messageBody hidden"> Body </p>
</div>
<div class="message">
<label class="slideDown"> Read </label>
<p class="messageBody hidden"> Body </p>
</div>
JS
$('.slideDown').click(function() {
$(this).next('.messageBody').slideToggle('slow');
});
Here's a working example: http://jsfiddle.net/rtZsJ/.
Upvotes: 4
Reputation: 11908
You are using the ids slideDown
and messageBody
multiple times, while ids have to be unique. What happens when you use ids more than once doesn't have to make any sense at all, as your document is just malformed.
Anyway, the way to fix this would be change the ids to be unique. One way would be like this:
<div class="message">
<label id="slideDown1"> Read </label>
<p id="messageBody1" class="hidden"> Body </p>
</div>
<div class="message">
<label id="slideDown2"> Read </label>
<p id="messageBody2" class="hidden"> Body </p>
</div>
js:
$('#slideDown1').click(function() {
$('#messageBody1').slideToggle('slow');
});
$('#slideDown2').click(function() {
$('#messageBody2').slideToggle('slow');
});
Upvotes: 2