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()
});
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/
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With