I think that the slice() is a bit hacky, and prone to breaking if I change my mind about the id names, but I wanted this to be generic so I could add types easily.

Is there maybe another / better way to do this just using CSS nesting the 'panels' inside the li elements?


   <ul id="type-select">
    <li><a id="type-1" href="#">1</a></li>
    <li><a id="type-2" href="#">2</a></li>

   <div id="panel-1" class="panel">blah</div>
   <div id="panel-2" class="panel">blah</div> 


function switchType(type){
    $("#type-select li a").removeClass("selected-type");

// initial state
$("#type-select li a").click(function(){switchType(this.id.slice(5))});

This kind of navigation is usually referred to as tabs or tabbed navigation. There are loads of ready scripts on the net for this - for exampe - since you are using jQuery - jQuery UI. But since this is really a quite trivial functionality, it's quite okay to implement it yourself.

To make the implementation cleaner, you can add a direct reference to the matching panel in the link. I would use the href attribute and refer to the panel using a URL hash. This has the advantage, that it will work without JavaScript or CSS by scrolling to the chosen panel.

You can drop the ids on the links and use a direct reference to them in the function.

<ul id="type-select">
  <li><a href="#panel-1">1</a></li>
  <li><a href="#panel-2">2</a></li>

Consider using the CSS :target pseudo class for the functionality:

.panel { display: none; }
.panel:target { display: block; }

And add JavaScript, for browsers that don't support it and to set the classes:

$("#type-select li a").click(function(){return switchType(this)});

function switchType(link){
    var hashPos = link.href.indexOf("#");
    if (hashPos >= 0) {
      // Parsing out the hash and removing '#', in case the href
      // attribute contains a complete URL, and in case some other
      // method than a CSS selector is used to find the panel
      var panelId = link.href.substring(hashPos + 1);

      $("#type-select li a").removeClass("selected-type");
      $("#" + panelId).addClass("selected-panel");   
    return false;

Don't forget to return false so the the default action of the link (which will lead to unnecessary scrolling) is canceled.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.