Maggie Sholes
Maggie Sholes

Reputation: 1

jQuery - using .slideToggle to toggle ONLY ONE thing at a time

All I want is for each list to toggle in and out when you click the span that precedes it. What happens now is that clicking one span toggles all the lists. I'm a jQuery beginner, but I feel like this is a really simple thing to do, so I'm frustrated that I can't figure it out. Also, there will be a LOT of these on the page, so I don't want to have to add a bunch of code for each new list.

This is my HTML:

<span class="rental">123 Main Street</span>
<ul class="rental-det">
    <li>2 bedrooms</li>
    <li>1 bathroom</li>
    <li>New carpets throughout</li>
    <li>All large kitchen appliances included</li>
    <li>In-unit washer and dryer</li>
    <li>Central air</li>
    <li>Dishwasher</li>
    <li>Renter responsible for all utilities</li>
</ul>

<span class="rental">321 Main Street</span>
<ul class="rental-det">
    <li>2 bedrooms</li>
    <li>1 bathroom</li>
    <li>New carpets throughout</li>
    <li>All large kitchen appliances included</li>
    <li>In-unit washer and dryer</li>
    <li>Central air</li>
    <li>Dishwasher</li>
    <li>Renter responsible for all utilities</li>
</ul>

So, again, I want to be able to click each span with a class of "rental" and toggle the list that immediately follows it.

Here is the jQuery I have been using:

$(document).ready(function(){
$('.rental').click(function() {
$('.rental-det').slideToggle()
});
}); 

I have also added display: none; to the .rental-det class to make them hidden by default.

Upvotes: 0

Views: 1273

Answers (2)

Daniel
Daniel

Reputation: 579

I would modify the HTML to move the spans to divs and place the details withing those divs.

$('.rental').on('click',function(){
    $(this).children().slideToggle();
});

This will simply display and javascript.

See my fiddle. http://jsfiddle.net/LeHMa/

Upvotes: 0

j08691
j08691

Reputation: 207891

Change

$('.rental-det').slideToggle()

to

$(this).next('.rental-det').slideToggle();

jsFiddle example

Your $('.rental-det').slideToggle() was selecting all lists of the .rental-det class, where you wantes to use instead $(this) and .next() to pick the list that followed the span that was clicked on.

Upvotes: 1

Related Questions