muudless
muudless

Reputation: 7532

Jquery - How to have multiple toggle on one page?

I'm new to Jquery and I was able to put together a simple toggle script. But I was disappointed to find out that it won't work with multiple toggles on one page.

I will potentially have up to 20 toggles.

  1. Is there a way to make this work without creating a new click function for each toggle?

  2. Right now when you cursor over the toggle trigger it doesn't turn into a hand. How would I turn the cursor into a hand?

Here is the code:

<script src="http://code.jquery.com/jquery-1.5.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("#toggle-trigger").click(function() {
        $("#toggle-wrap").toggle('slow');
    });
});
</script>

<p><a id="toggle-trigger">Click to toggle</a><p>
<div id="toggle-wrap">
    <div class="style-single">
        Random Text
    </div>
</div>


<p><a id="toggle-trigger">Click to toggle 2</a><p>
<div id="toggle-wrap">
    <div class="style-single">
        This doesn't work :(
    </div>
</div>

Upvotes: 2

Views: 14812

Answers (3)

Carls Jr.
Carls Jr.

Reputation: 3078

put a class on each toggle

ex
<a id="toggle-trigger1" class="trigger">Click to toggle</a>
<a id="toggle-trigger2" class="trigger">Click to toggle</a>
<a id="toggle-trigger3" class="trigger">Click to toggle</a>

in your script do this

$(".trigger").click(function() {
    //code here
});

Upvotes: 4

Jeff
Jeff

Reputation: 12418

Ian's answer works, however you can use this to avoid modifying your HTML markup. You'll have to change all of your ids (#) to classes (.) as well.

$(document).ready(function() {
    $(".toggle-trigger").click(function() {
        $(this).parent().nextAll('.toggle-wrap').first().toggle('slow');
    });
});

Full working example available at http://jsfiddle.net/sYPWN

One caveat: If you DO change your HTML markup sufficently, it may break your jQuery code. For instance, if you wrap your toggle-trigger in another div, you will need to change your jQuery to .parent().parent() (see http://jsfiddle.net/Xmvxf/1/ how the first toggle works, but the second doesn't)

I'm sure you get the idea, so you should be able to modify this to suit your needs.

Upvotes: 5

BraedenP
BraedenP

Reputation: 7215

The reason it's not working is because it uses IDs to differentiate between the states of the elements. Proper HTML shouldn't have more than one element with the same ID anyway; it's invalid.

Just change the toggle-wrap ID of the second element to something else, and then add a toggle for that new ID. Then it will work fine. :)

Upvotes: 1

Related Questions