Daniel Kellaway
Daniel Kellaway

Reputation: 189

Toggle between multiple divs jQuery

Between alternate divs with id's 1-3 how do I show the visability between each one when the user clicks the corresponding link? I only want one div to be shown at a time. Thanks.

<a>Link 1</a><br>
<a>Link 2</a><br>
<a>Link 3</a><br>

<div id="1">
    <p align="left">Content 1</p>
    </p>
</div>
<div id="2">
    <p align="left">Content 2</p>
    </p>
</div>
<div id="3">
    <p align="left">Content 3</p>
    </p>
</div>

Upvotes: 3

Views: 5666

Answers (1)

SimulatedBones
SimulatedBones

Reputation: 51

Add id's to your links so that you can add event handlers. Assuming you set your link id's to Link1, Link2, Link3, use the following code to wire up the event handlers:

$("#Link1").bind("click", function() {
   $("#1").show();
   $("#2").hide();
   $("#3").hide();
});

Code the event handler above for the other links (2 & 3), adjusting the logic so it shows the corresponding div, and hides the others.

A more robust solution:

<a class="myLink" divId="1">Link 1</a>

$(".myLink").bind("click", function() {
   $(".myDiv").hide();
   var divId = $(this).attr("divId");
   $("#" + divId).show();
});

Assuming your add the class "myDiv" to all your divs and the class "myLink" to all your links.

Working example: http://jsfiddle.net/8XZKx/1/

Upvotes: 5

Related Questions