<div id="showcase">
<ul class="nav">
<li><a href="#example" class="selected">Example</a></li>
<li><a href="#another">Another</a></li>
</ul>
<div class="first item" id="example">
This is the first item. By default it's shown.
</div>
<div class="item" id="another">
This is another item. By default it's hidden.
</div>
</div>
#showcase .item {
display: none;
}
#showcase .first {
display: block;
}
$(document).ready(function() {
var selected = $("#showcase .first"); // First is selected by default
$("#showcase .nav a").click( function() {
if($(this) != selected) {
$('#showcase .nav a.selected').removeClass('selected');
selected.hide();
selected = $($(this).attr('href'));
selected.show();
$(this).addClass('selected');
return false; // Stops link from jumping to the anchor
}
})
});
Refactorings
No refactoring yet !
bedlam.myopenid.com
February 13, 2009, February 13, 2009 00:13, permalink
If this idea is that only one 'item' should be visible at any given time, this should work with any number of links and items so long as the initial states are set.
<ul id="nav"> <li><a href="#one">Example</a></li> <li><a href="#two">Another</a></li> <li><a href="#three">Yet another</a></li> </ul> <div id="items"> <div class="first item" id="one"> This is the first item. By default it's shown. </div> <div class="item" id="two"> This is item two. By default it's hidden. </div> <div class="last item" id="three"> This is item three. By default it's hidden. </div> </div>
#items div {
display: none;
}
#items #one {
display: block;
}
$(document).ready(function() {
$('#nav a').click(function(){
var target = $(this).attr('href');
$('#items div').hide().each(function(){
targetSelector = '#' + $(this).attr('id');
if(targetSelector == target) {
$(targetSelector).show();
}
});
});
});
Is there a better way?