Reputation: 653
I have a series of links nested within a div. When one of those links is clicked, I'd like to hide the div with the link that was clicked and show another div. Then, if a link is clicked within that div, I'd like to change the div to yet another div.
The html looks like this:
<div id="main">
<div class="item"><a href="">Link to div A</a></div>
<div class="item"><a href="">Link to div B</a></div>
<div class="item"><a href="">Link to div C</a></div>
</div>
<div id="a" style="display:none;">Link to div <a href="">B</a> and <a href="">C</a></div>
<div id="b" style="display:none;">Link to div <a href="">A</a> and <a href="">C</a></div>
<div id="c" style="display:none;">Link to div <a href="">A</a> and <a href="">B</a></div>
I'm getting a little tripped up with the jQuery on this one. Does anyone have any advice on how to get this working with jQuery? Showing/hiding a div seems straight forward, but doing that again within the divs is confusing me.
Thanks!
Upvotes: 2
Views: 2815
Reputation: 68466
Not sure if this is exactly what you're after, but I put together this jsFiddle for you to have a look at. See here.
I added a few changes so you can identify which anchors relate to which div, so my HTML looks as follows:
<div id="main">
<div class="item"><a href="#" name="a">Link to div A</a></div>
<div class="item"><a href="#" name="b">Link to div B</a></div>
<div class="item"><a href="#" name="c">Link to div C</a></div>
</div>
<div class="item" id="a" style="display:none;">
Link to div <a href="#" name="b">B</a> and <a href="#" name="c">C</a>
</div>
<div class="item" id="b" style="display:none;">
Link to div <a href="#" name="a">A</a> and <a href="#" name="c">C</a>
</div>
<div class="item" id="c" style="display:none;">
Link to div <a href="#" name="a">A</a> and <a href="#" name="b">B</a>
</div>
Then, just a simple use of jQuery and it seems to work as you've described. Have a look at the jsFiddle I made and let me know if that's what you're after.
$(document).ready(function() {
// Hook up the first divs
$(".item a").click(function() {
// Get the target from the name of the anchor
var targetDiv = $(this).attr("name");
// Show the new div and hide the parent div
$("#" + targetDiv).css("display", "");
$(this).parents("div:last").css("display", "none");
});
});
Upvotes: 2