Ca3dc3f93730afb41d6753d8bf010a38

Is there a better way?

<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 !

Afdb6aa91430febdaea8020479bb4208

bedlam.myopenid.com

February 13, 2009, February 13, 2009 00:13, permalink

1 rating. Login to rate!

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();
			}
		});
	});
});

Your refactoring





Format Copy from initial code

or Cancel