Reputation: 6477
I have an alphabetical index that when clicked unhides a div that contains it's content.
Here is the HTML so I can explain properly:
<ul class="index">
<li>A</li>
<li>B</li>
<li>C</li>
</ul>
<div id="index-A" class="hide">A contents</div>
<div id="index-B" class="hide">B contents</div>
<div id="index-C" class="hide">C contents</div>
When a letter is clicked, I want to unhide it's content div and also hide any other ones that are visible.
How could I do that?
Here is what I have been trying, but am stuck at this point:
$('.index li').click(function(e) {
// somehow reference the content div using: "index-" + $(this).text()
});
Upvotes: 4
Views: 4740
Reputation: 8527
Demo http://jsfiddle.net/CzzG8/
$('.index li').click(function(e) {
var targetDiv = "#index-" + $(this).text();
$('div').show();
$(targetDiv).hide();
});
Upvotes: 0
Reputation: 96914
I like Martin's solution, but if you're using HTML5 it'd be nice to define the relationship between the links and their content in HTML rather than in Javascript:
<ul class="index">
<li data-show="#index-A">A</li>
<li data-show="#index-B">B</li>
<li data-show="#index-C">C</li>
</ul>
<div id="index-A" class="hide">A contents</div>
<div id="index-B" class="hide">B contents</div>
<div id="index-C" class="hide">C contents</div>
Javascript:
$(".index li").click(function(e) {
var div = $($(this).data("show")).show();
div.siblings("div").hide();
});
Upvotes: 3
Reputation: 2472
Try something like this:
Give each of your index items a class for the letter you wish it to reference:
<ul class="index">
<li class="A">A</li>
<li class="B">B</li>
<li class="C">C</li>
</ul>
<div id="index-contents">
<div id="index-A" class="hide">A contents</div>
<div id="index-B" class="hide">B contents</div>
<div id="index-C" class="hide">C contents</div>
</div>
And then you can find/show the index contents with:
$('.index li').click(function(e) {
// Hide all
$('#index-contents .hide').hide();
// Find the class of the clicked index item
var index = $(this).attr('class');
// Show the index's contents
$('#index-contents').children('#index-'+index).show();
});
Upvotes: 0
Reputation: 11198
Very simply:
$('.index li').click(function(e) {
$('div.hide').hide();
$('#index-' + $(this).text()).show();
});
Upvotes: 0
Reputation: 26183
Sounds like you are looking for this:
$('.index li').click(function(e) {
var div = $('#index-'+ $(this).text()).show();
div.siblings('div').hide();
});
You can see a working example here: http://jsfiddle.net/ktsfs/1/
Upvotes: 6