Use your left/right keys to browse tutorials
Simple jQuery tabs

Simple jQuery tabs

1 Star2 Stars3 Stars4 Stars5 Stars
Posted on July 22, 2009

This tutorial looks into creating a really simple tabbed interface using just plain HTML and CSS with the functionality and interface manipulated using jQuery. Tabbed interfaces are great for maximizing the amount of space you have on your site.

Lets take a look at whats going on. We start with the document ready function. The first line of code hides all the tab containers, we then show the first one, and add the class ‘active’ to the first ‘li’ in the tab headers. Then whenever a tab is clicked it simply remove the class ‘active’ from all the tabs, then add it to the tab thats been clicked. We then take the href from the clicked tab and show it. Simple as that! You can get the complete file by grabbing the download and the demos at the bottom also.

The Code

$(document).ready(function(){
$('#tabs div').hide();
$('#tabs div:first').show();
$('#tabs ul li:first').addClass('active');

$('#tabs ul li a').click(function(){
$('#tabs ul li').removeClass('active');
$(this).parent().addClass('active');
var currentTab = $(this).attr('href');
$('#tabs div').hide();
$(currentTab).show();
return false;
});
});

The HTML

 <div id="tabs">
    <ul>
      <li><a href="#tab-1">This is Tab 1</a></li>
      <li><a href="#tab-2">Tab Two</a></li>
      <li><a href="#tab-3">Tab Three</a></li>
      <li><a href="#tab-4">Tab Four</a></li>
    </ul>
    <div id="tab-1">
      <h3>This is a really simple tabbed interface</h3>
      <p><img src="http://papermashup.com/demos/jquery-gallery/images/t1.png" width="120" height="120" class="thumbs"/> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur enim. Nullam id ligula in nisl tincidunt feugiat. Curabitur eu magna porttitor ligula bibendum rhoncus. Etiam dignissim. Duis lobortis porta risus. Quisque velit metus, dignissim in, rhoncus at, congue quis, mi. Praesent vel lorem. Suspendisse ut dolor at justo tristique dapibus. Morbi erat mi, rutrum a, aliquam nec, mattis semper, leo. Maecenas blandit risus vitae quam. Vivamus ut odio. Pellentesque mollis arcu nec metus. Nullam bibendum scelerisque turpis. Aliquam erat volutpat. <br/>
        <a href="http://feeds2.feedburner.com/AshleyFord-Papermashupcom">Subscribe to my feed here</a> </p>
    </div>
    <div id="tab-2">
      <h3>Tab 2</h3>
      <p><img src="http://papermashup.com/demos/jquery-gallery/images/t2.png" width="120" height="120" class="thumbs"/> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur enim. Nullam id ligula in nisl tincidunt feugiat. Curabitur eu magna porttitor ligula bibendum rhoncus. Etiam dignissim. Duis lobortis porta risus. Quisque velit metus, dignissim in, rhoncus at, congue quis, mi. Praesent vel lorem. Suspendisse ut dolor at justo tristique dapibus. Morbi erat mi, rutrum a, aliquam nec <br/>
        <a href="http://feeds2.feedburner.com/AshleyFord-Papermashupcom">Subscribe to my feed here</a></p>
    </div>
    <div id="tab-3">
      <h3>Tab 3</h3>
      <p><img src="http://papermashup.com/demos/jquery-gallery/images/t3.png" width="120" height="120" class="thumbs"/> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur enim. Nullam id ligula in nisl tincidunt feugiat. Curabitur eu magna porttitor ligula bibendum rhoncus. Etiam dignissim. Duis lobortis porta risus. Quisque velit metus, dignissim in, rhoncus at, congue quis, mi. Praesent vel lorem. Suspendisse ut dolor at justo tristique dapibus. Morbi erat mi, rutrum a, aliquam nec, mattis semper, leo. Maecenas blandit risus vitae quam. Vivamus ut odio.<br/>
        <a href="http://feeds2.feedburner.com/AshleyFord-Papermashupcom">Subscribe to my feed here</a></p>
    </div>
    <div id="tab-4">
      <h3>Tab 4</h3>
      <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur enim. Nullam id ligula in nisl tincidunt feugiat. Curabitur eu magna porttitor ligula bibendum rhoncus. Etiam dignissim. Duis lobortis porta risus. Quisque velit metus, dignissim in, rhoncus at, congue quis, mi. Praesent vel lorem. Suspendisse ut dolor at justo tristique dapibus. Morbi erat mi, rutrum a, aliquam nec, mattis semper, leo. Maecenas blandit risus vitae quam. Vivamus ut odio. Pellentesque mollis arcu nec metus.<br/>
        <a href="http://feeds2.feedburner.com/AshleyFord-Papermashupcom">Subscribe to my feed here</a></p>
    </div>
  </div>

demodownload



Recent shares

More tutorials from Papermashup
Comments
86 discussions around Simple jQuery tabs
  1. waqas cheema says:

    easy way to make menus for users but is there any way to use drag and drop on submenus as well.
    please also add support for submenus as well.
    thanks

  2. Kevin says:

    No, I need to use Divs inside the tabs, how do i modify this to show other divs contained with each tab?

    $(document).ready(function(){
    $(‘#tabs div’).hide();
    $(‘#tabs div:first’).show();
    $(‘#tabs ul li:first’).addClass(‘active’);

    $(‘#tabs ul li a’).click(function(){
    $(‘#tabs ul li’).removeClass(‘active’);
    $(this).parent().addClass(‘active’);
    var currentTab = $(this).attr(‘href’);
    $(‘#tabs div’).hide();
    $(currentTab).show();
    return false;
    });
    });

  3. Kevin says:

    I am trying to use inside the tabs to divide up the space and it does not work?

    Do I need to define the div are first?

  4. zoran says:

    Hi,
    Thanks a lot for sharing this really easy implementation that doesn’t require any external plugins or libraries.. jquery is already enough:)
    cheers
    Zoran

  5. IJas says:

    Use of .sIbling()

    (function()
    {
    $(‘.tab div’)
    .first().addClass(‘active’)
    .siblings(‘div’).hide();

    $(‘.tab ul li a’).click(function(e)
    {
    e.preventDefault();

    $(this)
    .parent().addClass(‘active’)
    .siblings(‘li’).removeClass(‘active’);

    var currentTab = $(this).data(‘tab’);
    $(currentTab).show().siblings(‘div’).hide();
    });
    })();

  6. Elias says:

    It works great! Only for some reason, after the third div script code adds quotation marks “” immediately after the active divas and shifts all the way down on the value of the string. Have any suggestions? Why?

    It works great! Only for some reason, after the third div script code adds quotation marks “” immediately after the active divas and shifts all the way down on the value of the string. Have any suggestions? Why? The page on which it occurs: http://www.vozdvizhenka.info/vozdvizhenskaya/36/

    Thank U!

  7. mex says:

    thank u sir

  8. Kevin says:

    Has anyone been able to display 2 sets of tabs on the same page, if so can you let me know what code to change.

  9. Pingback: A Complete List of Code I Didn’t Write : Create Awesome

  10. ali says:

    thanks alot , regards

  11. fanta says:

    I’m getting “uncaught exception: Syntax error, unrecognized expression” error, any ideas what can be wrong?

  12. SteeL says:

    Im sorry to say but ur script makes every otehr DIV inside TABS display:none. which is a very hectic to set css for each div block !important.

    This one and old one is still the best for my use http://jqueryfordesigners.com/demo/tabs.html

  13. There’s a small improvement; use $(‘#tabs > div’).hide();
    instead of $(‘#tabs div’).hide(); that way, it works even if you put divs inside your divs (basically, only the ‘bigger’ div is hidden; your code appears to hide ALL divs inside tabs (including inner divs) but then only shows the ‘bigger’ one)

    And thanks ! this is cool and easy to understand

  14. Thanks for some great code. I was tearing my hair out trying to set up tabs using jquery and couldn’t get it to work. Your code has worked first time and will be used in my new web site, currently under construction. I really appreciate you sharing your knowledge and expertise. Many thanks once again.

  15. ChefBob says:

    I am using this code, but the pages have huge scrolls in them: exactly the height of all the tabs combined. How can I fix this? Thanks!

    • It’s because your inner divs, which most likely have a lot of content, are not being hidden.

      Orlando Karam made a great great explanation in a comment on this post and I quote him:

      use $(‘#tabs > div’).hide(); instead of $(‘#tabs div’).hide();

      - that way, it works even if you put divs inside your divs (basically, only the ‘bigger’ div is hidden; your code appears to hide ALL divs inside tabs (including inner divs) but then only shows the ‘bigger’ one)

      Cheers!

    • It’s because your inner divs, which most likely have a lot of content, are not being hidden.

      Orlando Karam made a great great explanation in a comment on this post and I quote him:

      use $(‘#tabs > div’).hide(); instead of $(‘#tabs div’).hide();

      If you look further up a bit he puts a great reference as to why.
      Cheers!

  16. thanks for this nice script, i’ll use it on my news site. This will perfectly fit for my news headlines.

  17. Ashis says:

    Works like a Charm. GREAT !!

  18. Ashis says:

    Works like a charm !!. GREAT

  19. James says:

    Nice and simple, love it. Was looking at using JQuery UI for a custom control panel, but this is much leaner. Thanks!

  20. Pauly says:

    Thank you for this really simple solution! Jquery UI is way to complicated

  21. Steven Annan says:

    No need for help on the code additions any more but thanks for setting me on the right path. I’ve found a different script that does what I need with history support and direct links to the tabs. It’s still pretty simple as well.

    Thought I’d post the link here in case anyone else is looking for this functionality. Hope this is OK.

    http://www.queness.com/post/9503/create-a-tab-interface-with-browser-history-and-url-support

  22. Steven Annan says:

    Hi Ashley
    Using your tabs for a website I’m putting together and wondered if you could help me out, I’ve modified the code a bit to allow divs inside each tab and to fade between the tabs. As well as adding the #tag for each tab to the address bar.

    What I’d like to be able to do is when the site is accessed via an external link
    eg: http://www.randomwebsite.com/#contact

    It will open the contact tab as the first tab and set the matching li to active.

    Unfortunately I Can’t work it out.

    Adding
    if(document.location.hash){ }

    with a rule to the doc ready function probably holds the key but I’m not sure what rule.

    Any help appreciated.

    Code can be found here: http://pastebin.com/DSvCFffQ

    Thanks

  23. Hal says:

    First, I want to say this is a great tutorial. I was quickly able to start using tabs, then bend them to my will. Looking at the amount of content I’m trying to fit on the page, I need to be able to scroll within these tabs. The site I’m working on is highly stylized and the normal scroll bars (only vertical needed) just won’t work – too large and clunky. So, I’ve been trying to use jScrollPane.

    When I use jScrollPane, the initial load looks great, however switching tabs looses all content. I cannot figure out how to get it back.

    Here’s what I’ve been using for slider reference…
    - Basic jScrollPane demo: http://jscrollpane.kelvinluck.com/basic.html

    What I’ve tried so far:
    Beyond the file needed to run jScrollPane (jquery.jscrollpane.min.js), the main call is this – ” $(‘.scroll-pane’).jScrollPane(); ” I have attempted putting it in various places within the code provided in the example above, but the only thing that comes close to working is to have it as the final line in the code (after ” return false; }); ” ).

    If there’s anything you can suggest to use stylized scroll bars within the tabs (that doesn’t crash the content upon selecting a new tab), that would be fantastic. Any help would be much appreciated. Thank you.

  24. All inside any of the main tab are hidden. Here is a modification I made to allow s inside the tab :

    $(document).ready(function(){
    $(‘#tabs div.tab-parent’).hide();
    $(‘#tabs div.tab-parent:first’).show();
    $(‘#tabs ul li:first’).addClass(‘active’);

    $(‘#tabs ul li a’).click(function(){
    $(‘#tabs ul li’).removeClass(‘active’);
    $(this).parent().addClass(‘active’);

    var currentTab = $(this).attr(‘href’);
    $(‘#tabs div.tab-parent’).hide();
    $(currentTab).show();

    return false;
    });
    });

    Overview
    How It Works
    Clinical References

    tab 1

    tab 2

    tab 3

    • sri says:

      Thanks for the tip Jason. Also, add class=”tab-parent” for the div tabs for this to work. thanks

      —–

      —-
      Regards,
      Sri

    • jobish says:

      its working fine

      $(‘#tabs div’).hide();
      $(‘#tab-1 div’).show();
      $(‘#tab-1′).show();

      $(‘#tabs ul li:first’).addClass(‘active’);

      $(‘#tabs ul li a’).click(function(){
      $(‘#tabs ul li’).removeClass(‘active’);
      $(this).parent().addClass(‘active’);

      var currentTab = $(this).attr(‘href’);
      $(‘#tabs div.tab-parent’).hide();
      $(‘#tabs div’).hide();

      $(currentTab).show();
      $(currentTab+” div”).show();

  25. Alex says:

    im having trouble with the way it looks when the tabs start wrapping to the next line… any solutions?

  26. y8 games says:

    I need it. Thanks a lot

  27. Danny says:

    Anyone figure out how to link to a specific tab from an external link, and an internal link?

    Earl P says he figured it out, but when implementing his syntax, it does not work.

    Does anyone have any idea how to do this with a clear example? What will teh actual link look like? I have seen other sites say you need to add two lines of code to the Document Ready JS…but no one has a clear answer as how to create the URL to achieve this. Someone on another site said you link to it lik an anchor tag….that also did not work.

    Any help please.

  28. Syed Imtiaz Waris Warsi says:

    very easy, very simple. best of luck.

    Regards

  29. Cory Deere says:

    How could one use two or three different images within the tabs? So you could achieve an image active state while differentiating between tabs for the different images. it seems that something in the jquery would have to be changed? I’ve tried wrapping the tabs in their own divs and styling with css but can’t get them to work independently. Any Help would be awesome!

    Thanks!

  30. Rajeev Sharma says:

    Simple and sweet thanks :)

  31. Istria says:

    Very nice tab, thanks for sharing!

  32. Andrew says:

    transition is handled by adding fadeIn to the current tab, ie…
    As this is a simple transition it’s not necessary to link to the easing script.

    $(currentTab).fadeIn(400).show();
    or
    $(currentTab).fadeIn(‘fast’).show();

  33. Read says:

    Hey,

    I absolutely loved this tutorial. It was so simple and that is exactly what everyone is looking for. I do have a quick question though, how would I go about adding unique images to each tab. I have already created the classes which contain CSS for the specific buttons. The problem is when I hover tab two and back to one, tab two stays selected while the active tab (tab one) doesn’t not appear to be active.

  34. Red says:

    Hi,

    Just to add to the above comment in regards to having the tabs link as individual links. I used the JS code you suggested and it works, however each tab now pulls in all of the content for all of the tabs. So lets say in Tab 1 I have 3 x images a,b & c. Tab 2 has 3 different images d,e & f. Once I implement you JS suggestion a,b,c,d,e,f images get displayed in the tabs. strange!

    Would love some help!

    Thanks red

  35. Red says:

    Hi,

    I was wondering if there was a way to link each tab content with a # mark or some identifier? Basically I would like to create a unique URL for each tab content so I could post that link to that particular content on facebook or twitter for example.

    Would really appreciate some help

    Thanks Red

  36. Aayush says:

    The best tabs tutorial…I needed simple and I got simple….I spent a long time making a very cool one with codaSlider and then ended up using these…Amazing…

  37. Chris says:

    I don’t see how you would create a link to the tab from another page in this sample. I’ve looked all over and I can’t figure out how to do this.

  38. bao says:

    nice tutorial, thanks

  39. I fixed the div, now I cannot put lists in either

  40. Cannot put div within a div either, very frustrating

  41. putude says:

    hello, I am newbie.
    Want to ask about jquery tab.
    I have a problem when there is DIV inside the container.
    ….
    ..content….

    the content won’t appear.
    Please help me.

    Thank you

  42. Aman says:

    hi
    your tutorial is really helpful. I have also 15+ eyes Caching Jquery tabs please see here:-

    http://jquery13.blogspot.com/2010/08/15-eyes-catching-jquery-tabs.html

    Thanks
    Aman

  43. blogregator says:

    Great tutorial! Thanks!

  44. Pingback: jQuery: збірка плагінів та туторіалів |Створення сайтів, Seo| Мегаблог

  45. Pingback: Twitted by delicious50

  46. Earl P says:

    @Ashley, It works, but a bit different then I thought.

    the string is blabla.html?tab=1&#4

    One weird thing is that once you pass the string to tab blabla.html?tab=1&#4, I can’t seem to pass to another tab from the url:

    example: if I type in blabla.html?tab=1&#2 from the blabla.html?tab=1&#4 page… it won’t pass. I’m not sure I’ll need to, but something I noticed when playing around with it. nice tutorial.

    -E.P.

  47. Earl P says:

    @Ashley, nice code! I’m going to replace some spry ish I have right now. I have nested tabs that I need to link to from another page, this should work. I hoping to be able to pass something like: blabla.html?tab=1#TabbedPanels1&#4

    I’ll let you know if it works….
    thanks.
    E.P.

  48. audrey says:

    hello,

    thanks for the tutorial !
    i’m trying to put some columns of text inside the tab-1 but when I use a div inside the tab div it does not appear.

    someone in the forum suggested to write $(’#tabs > div’).hide();
    instead of
    $(’#tabs div’).hide();

    I did it but I still don’t manage to put another div element inside one of the tabs…

    what should I do ?

    thank you for your help,

    audrey

    • Ashley says:

      @Audrey i cant understand why you’re having problems. If you like you can email me your code to ashley at dotdashcreate dot com and i can take a look for you.

  49. wpfeed says:

    the best jQuery tabs to use!!!

  50. uppercanuck says:

    Nice work! Has anyone modified the script to fade out a tab on mouseout?

  51. Jacob Miller says:

    I would like to know if its possible to have scroll bars in jQuery tabs?

    • Ashley says:

      @Jacob you could just set the contents of the container div to overflow:scroll; with a bit of CSS make sure you set a height on the div and you’ll see the scroll bar on the right.

  52. joseph says:

    thanks for your great example
    I don’t know to to call it in your code? so, i need to access tab-3 from another page ? what can i do to make the page open in this tab?

  53. slacey says:

    Thanks Ashley! I think this will work, although I’m bummed I have to change all my code. Your tabs were so nice and clean!

    But thank you for helping me find this one.

    • Ashley says:

      @slacey no problem :) depending on your JavaScript knowledge you might be able to edit my tabs to work with the demo i posted.

      at a glance you would need to add the below code:

      // Determine which tab should show first based on the URL hash
      var panelLocation = location.hash.slice(1);
      if(panelLocation){
      var panelNum = panelLocation;
      }else{
      var panelNum = ’1′;
      }

  54. slacey says:

    Thanks for this! It’s exactly what I needed and works very well. You said you could dig out an example of linking directly to a certain tab from an outside page. Could you please do that? I really need to do this and can’t find the code for this specific tab system.

    Please and thank you!

  55. Pingback: Dubo.cl » Blog Archive » links for 2009-09-22

  56. Vicky says:

    NICE Graphics..Thanks for the TUT.

  57. Marc Mcleod says:

    Is it possible to link directly to one of the tabs? E.g. If I wanted to link directly to tab #3 from another page, how could this be achieved?

  58. That was, another <div> element ;-)

  59. One Suggestion:
    add the immediate-child > selector to the rules

    $(‘#tabs > div’).hide();
    instead of
    $(‘#tabs div’).hide();

    In case the user wants to put another element inside of one of the tabs.
    Otherwise – perfect, simple, thanks!

  60. Whack Design says:

    Great post! Thanks for taking the time to write it. I have one question for you, I want some of the ‘s in the to actually link to outside links how can I do that?

    Thanks in advance

  61. Great simple tab list, will re-work for a site i’m currently working on!

  62. Maybe adding the following:
    a { outline:none; }

    Will help with the tabs showing the outline.

  63. Jason Warner says:

    This one seems more intuitive and clear:

    http://www.sohtanaka.com/web-design/simple-tabs-w-css-jquery/

    • Ashley says:

      @jason I think you’ll find the code is pretty much exactly the same. but thanks for the link I’m sure people will find it useful :)

  64. Cool! Thanks for the tut :)

  65. Pingback: 22 fresh design and development related links for you ;) « Adrian Zyzik’s Weblog

  66. Pingback: Simple jQuery tabs | Papermashup.com « Netcrema - creme de la social news via digg + delicious + stumpleupon + reddit

  67. mahesh says:

    Nice tutorial,
    Nice demo,
    Can you explain how to implement browser history management for tabs with cookie,
    i am awaiting to your post

  68. Ben says:

    Cool, I was looking to do something like this a few days ago. Ended up using the jQuery UI though

  69. Simple is definitely the key word here, fantastic tutorial and very easy to follow.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>



Never miss an update from Papermashup

Get notified about the latest tutorials and downloads.

Subscribe by Email

Get alerts directly into your inbox after each post and stay updated.
Subscribe
OR

Subscribe by RSS

Add our RSS to your feedreader to get regular updates from us.
Subscribe

Get in contact

Please use the form below to get in contact. If your question is related to a free script download, please use the comments on the article page as community members are more likely to respond quicker than I can personally.

About Me

I'm Ashley Ford, Co-founder and Technical Director at Harkable.com London, UK. Previously I worked at InMobi, Spotify and MySpace. My interests include photography and making short videos I'm also an avid F1 fan. I'm always working on side projects. Here are a few: Easy Poll, We Deliver.



What do you specialise in?

I spend a lot of time coding in PHP and MySQL, as well as front end XHTML and CSS. I also specialise in javascript and the jQuery framework as well as being an avid designer. You can find me on dribbble

Interested in advertising?

If you'd like to advertise on Papermashup.com please get in touch via the contact link below for advertising opportunities.

How do I contact you

You can contact me here. and I'm available for consultation, freelance, programming book reviews.

Get on the mailing list

Join over 3000 people who have subscribed to the Papermashup inbox message, and be the first to find out about tutorial, competitions and giveaways.