jQuery Tabs

18Jan

Background

Tabbing has been common place on the Internet for some time now. Today web sites will make use of tabbing without the page having to reload with the addition of JavaScript.

For this tutorial I have created two screencasts demonstrating how to quickly apply a dash of jQuery to different layouts of markup, which, if the markup is well designed, it will automatically degrade nicely without JavaScript enabled. In a future article we will cover default browser functionality (i.e. supporting back, forward and bookmark buttons) and saving tab states.

Conventional and simple markup

Watch the jQuery tabs screencast - part 1 (flash version)

(QuickTime version is approx. 25Mb, flash version is streaming)

View demo and code used in screencast

Typical tabbing structure, and the one used in the demo is usually marked up as follows:

<div class="tabs">
  <!-- tabs -->
  <ul class="tabNavigation">
    <li><a href="#message">Send a message</a></li>
    <li><a href="#shareFile">Share a file</a></li>
    <li><a href="#arrange">Arrange a meetup</a></li>
  </ul>

  <!-- tab containers -->
  <div id="message">
    <p>Lorem ipsum dolor sit amet.</p>
  </div>
  <div id="shareFile">
    <p>Sed do eiusmod tempor incididunt.</p>
  </div>
  <div id="arrange">
    <p>Ut enim ad minim veniam</p>
  </div>
</div>

Here's the jQuery used, though slightly adapted from this screencast:

$(function () {
    var tabContainers = $('div.tabs > div');
    
    $('div.tabs ul.tabNavigation a').click(function () {
        tabContainers.hide().filter(this.hash).show();
        
        $('div.tabs ul.tabNavigation a').removeClass('selected');
        $(this).addClass('selected');
        
        return false;
    }).filter(':first').click();
});

Real World example

Watch the jQuery tabs screencast - part 2 (flash version)

(QuickTime version is approx. 30Mb, flash version is streaming)

View demo and code used in screencast

Chris Mahon requested a tutorial that explained how to apply tabbing to markup that doesn't follow the above markup convention.

In his case, the tabs were in a different DIV to the tab containers, in addition, one item in the UL wasn't a tab, but used to link to a different page.

Here's the jQuery tab code used:

$(function () {
    var tabs = [];
    var tabContainers = [];
    $('ul.tabs a').each(function () {
      // note that this only compares the pathname, not the entire url
      // which actually may be required for a more terse solution.
        if (this.pathname == window.location.pathname) {
            tabs.push(this);
            tabContainers.push($(this.hash).get(0));
        }
    });
    
    $(tabs).click(function () {
        // hide all tabs
        $(tabContainers).hide().filter(this.hash).show();
        
        // set up the selected class
        $(tabs).removeClass('selected');
        $(this).addClass('selected');
        
        return false;
    });
});

Taking it further

These screencasts are really designed to help you understand the thought process and how to go about writing the code for the tabs.

In a future article I will explain how to convert this code to a plugin that can be reused on your projects, and what to watch out for when making the code reusable.

Of course, you can always use the jUI Tabs to accomplish the task if you require more dynamic functionality.

5 Trackbacks/Pingbacks

  1. Pingback: 37 More Shocking jQuery Plugins on April 9, 2008
  2. Pingback: 37个更加出色的jQuery插件 | 帕兰映像 on April 10, 2008
  3. Pingback: e-octante » 37 plugins para jQuery on April 11, 2008
  4. Pingback: 37 plugins para jQuery « Think Free - Linux.Php.Java.ME.Movies on April 11, 2008
  5. Pingback: 37 More Shocking jQuery Plugins | SEO & Web Design on May 6, 2008

18 Comments

  1. Rick
    January 19, 2008 at 18:26

    I would much prefer to see all the code on the page, rather than in the overflowing div's. Makes it easier to understand if I can see it in context.

    Also, I couldn't find the CSS for the demo. It would be great if you could provide a download of all files (and graphics, if applicable) for tutorials, so they can be viewed and worked on locally.

    Once final thing... love the video demos, showing just how the code is put together, along with the audio explanation of what you're doing!

    Thanks for the work!

    Rick

  2. Remy
    January 19, 2008 at 20:52

    Rick - thanks for the feedback.

    The overflow was to do with the theme - so I've binned the options for colours and layout, and defaulted it to fluid width. Hopefully this will make seeing the code easier.

    I'll also add links to the source code used in both demos.

    Cheers.

  3. mrm
    January 19, 2008 at 22:33

    The html in my previous post got stripped. What I meant to say whas that the UL element should have class="tabNavigation".

  4. Remy
    January 19, 2008 at 23:17

    @mrm - cheers - I've updated that now.

  5. Rick
    January 21, 2008 at 03:40

    Much nicer and more usable display of the code, Remy.

    Thanks!

    Rick

  6. Jonathan
    February 13, 2008 at 21:51

    I'm loving this method, as for my current project I don't really require any dynamic functionality or the significant numbers of options that the UI plugin provides. I do have one question, though.

    Is it possible to switch the tab based on the querystring value (i.e. http://example.com/page.html?tab=tabname)? If so, how can I achieve this?

    Thanks so much! Jonathan

  7. Max
    February 18, 2008 at 20:53

    Great tutorial, thank you very much! Here come a couple of 'eye-rolling' newbie questions:

    1. Has this been tested in various browsers? I've tried it in Firefox, IE, as well as in Opera, and it's not working as expected in the latter two.

    2. I've tried looking up more info on the '.hash' selector (and selecting with 'this.hash' in general), and couldn't find much. Any links to resources on that would be greatly appreciated.

    Thanks!

  8. Remy
    February 19, 2008 at 01:12

    @Max - regarding testing, I tend to test in Firefox, Safari and IE (usually 7). I've looked at the examples in Opera, and the second one is not working for some reason (that I'll look in to).

    I've also noticed that Chris Mahon's original CSS for the 'ThumbSlap' page has been taken down - so I'm following up to get that fixed so it matches the screencast.

    Finally, the .hash that I used: it's not a selector. In the context of the click event, 'this' is set to the anchor element. The anchor element has an attribute of 'href'. As a DOM node, it also has a property called 'hash'. This is the part in the href from the hash symbol onwards (i.e. mypage#tab1 - #tab1 is the hash).

    As such, we're able to use the variable this.hash to use it as the element ID we're searching for using jQuery.

    I hope that helps.

  9. Max
    February 19, 2008 at 15:05

    Remy,

    Thank you very much for your prompt response! That definitely clears things up. I guess if there's no click event then I'll have to find an alternate way of getting to the right tab container div.

    Thanks again for the great tutorial!

  10. tom
    March 11, 2008 at 22:19

    Thanks for the tutorial. I have found that the second method you use does not work in either IE6 or IE7? Am I alone in finding this?

    I have attempted a similar mehtod it cannot get it to work. It works ok in firefox and in safari but IE - not im afraid. Any suggestions?

    Here is my attempt;

    www.tomhorner.com/websites/starkey/productmenu.php

  11. Max
    March 12, 2008 at 15:35

    Tom,

    What could be the problem is the bit where pathnames are being compared. I found out that IE and Firefox give out different strings for location.pathname and this.pathname.

    I recommend you read the section titled "What's in a path name?" at this address: http://www.learningjquery.com/2007/08/animated-scrolling-for-same-page-links

    It also contains a nice fix which got my script working.

    Hope it helps!

  12. Max
    March 12, 2008 at 15:42

    Is it just me or does clicking on tab links in Opera throws you to the top of the page? I really don't get why, since the function returns false... Any ideas?

    By the way, is there a tool out there which is similar to Firebug, only for Opera?

  13. tom
    March 15, 2008 at 20:19

    Hey Max, thanks so much for the link - worked a treat! Solved my problem straight away.

  14. Rod
    March 25, 2008 at 11:24

    Hi Remy, I think this a great source for many people. I personally love the way you show your ideas and code. I´m a designer who has now a complete new world of possibilities thanks to jquery and sites like yours. Please keep going! Regarding these tabs, which would be the code needed to load each tab content from external pages? Do you think the hash feature would still work with such a change? Thanks!

  15. eph
    April 14, 2008 at 20:34

    hey this is great! is the jquery.js free to use with citations? and if so what type of citing is required?

  16. Travis
    April 15, 2008 at 22:16

    Hey Remy, Fantastic tutorial and site all around. Love it.

    Any status updates on the stylesheet for:

    http://jqueryfordesigners.com/demo/thumbslap.html

    I'd really like to see the demo in action, style and all. Thanks.

  17. Marcus
    April 18, 2008 at 22:04

    Hey Remy,

    First off, love the site!

    Second, for some reason, the I can't get the first example of jQuery Tabs to play nicely in IE6. (IE6 you drive me flippin' batty!)

    Any ideas? Thanks man!

  18. krew
    April 22, 2008 at 05:14

    I just wanted to thank you for putting together such a great jQuery resource. The tutorials you've posted have been very helpful in my site development, and I look forward to seeing what you come up with next.

Leave a comment