Pure Javascript Tabs with HTML 5 and CSS3

By | May 2, 2011

So lots of people have done jQuery tabs or other versions of tabbed navigation but I wanted to update this using modern techniques. So we’re going to use an HTML 5 wrapper document and style the tabs using CSS3. Then in this tutorial I’m going to show you how to create the functionality using only javascript no libraries like jQuery or Mootools. In the second part to the tutorial I will then show you how to create a jQuery plugin with the code we’ve written. Sound good? I hope so.

View DemoDownload Source

The HTML









  • Page 1
  • Page 2
  • Page 3

Page 1

Pellentesque habitant morbi tristique senectus...

Page 2

Pellentesque habitant morbi tristique senectus...

Page 3

Pellentesque habitant morbi tristique senectus...

Nothing new here really, we start with the common HTML5 doctype stuff and a wrapper div just for styling. Then we have the tabsContainer div that does what it says this is the container for the two main tab divs. So first the tabs themselves. These are inside the #tabs div and are contained inside a ul element. Each of the tabs has an id that will be used to target the tabs later.

Next is the tabscontent div this holds three divs (for the three tabs but this could be extended by add more divs here and more tabs to the list above). Each of these has the same class name to be used for styling and a different id which will be used to target the individual divs in the javascript. Then at the bottom I use the lazy HTML5 syntax for bringing in scripts.

The CSS

* {
	margin:0;
	padding:0;
}

body {
	background:url(../../images/background.png) top left;
	font: .8em "Lucida Sans Unicode", "Lucida Grande", sans-serif;
}

h2{ 
	margin-bottom:10px;
}

#wrapper{
	width:720px;
	margin:40px auto 0;
}

#wrapper h1{
	color:#FFF;
	text-align:center;
	margin-bottom:20px;
}

#wrapper a{
	display:block;
	font-size:1.2em;
	padding-top:20px;
	color:#FFF;
	text-decoration:none;
	text-align:center;
}

#tabContainer {
	width:700px;
	padding:15px;
	background-color:#2e2e2e;
	-moz-border-radius: 4px;
	border-radius: 4px; 
}

.tabs{
	height:30px;
}

.tabs > ul{
	font-size: 1em;
	list-style:none;
}

.tabs > ul > li{
	margin:0 2px 0 0;
	padding:7px 10px;
	display:block;
	float:left;
	color:#FFF;
	-webkit-user-select: none;
	-moz-user-select: none;
	user-select: none;
	-moz-border-radius-topleft: 4px;
	-moz-border-radius-topright: 4px;
	-moz-border-radius-bottomright: 0px;
	-moz-border-radius-bottomleft: 0px;
	border-top-left-radius:4px;
	border-top-right-radius: 4px;
	border-bottom-right-radius: 0px;
	border-bottom-left-radius: 0px; 
	background: #C9C9C9; /* old browsers */
	background: -moz-linear-gradient(top, #0C91EC 0%, #257AB6 100%); /* firefox */
	background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#0C91EC), color-stop(100%,#257AB6)); /* webkit */
}

.tabs > ul > li:hover{
	background: #FFFFFF; /* old browsers */
	background: -moz-linear-gradient(top, #FFFFFF 0%, #F3F3F3 10%, #F3F3F3 50%, #FFFFFF 100%); /* firefox */
	background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#FFFFFF), color-stop(10%,#F3F3F3), color-stop(50%,#F3F3F3), color-stop(100%,#FFFFFF)); /* webkit */
	cursor:pointer;
	color: #333;
}

.tabs > ul > li.tabActiveHeader{
	background: #FFFFFF; /* old browsers */
	background: -moz-linear-gradient(top, #FFFFFF 0%, #F3F3F3 10%, #F3F3F3 50%, #FFFFFF 100%); /* firefox */
	background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#FFFFFF), color-stop(10%,#F3F3F3), color-stop(50%,#F3F3F3), color-stop(100%,#FFFFFF)); /* webkit */
	cursor:pointer;
	color: #333;
}

.tabscontent {
	-moz-border-radius-topleft: 0px;
	-moz-border-radius-topright: 4px;
	-moz-border-radius-bottomright: 4px;
	-moz-border-radius-bottomleft: 4px;
	border-top-left-radius: 0px;
	border-top-right-radius: 4px;
	border-bottom-right-radius: 4px;
	border-bottom-left-radius: 4px; 
	padding:10px 10px 25px;
	background: #FFFFFF; /* old browsers */
	background: -moz-linear-gradient(top, #FFFFFF 0%, #FFFFFF 90%, #e4e9ed 100%); /* firefox */
	background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#FFFFFF), color-stop(90%,#FFFFFF), color-stop(100%,#e4e9ed)); /* webkit */
	margin:0;
	color:#333;
}

So forget about all the basic styling and lets start with .tabs. Next we set the tabs ul to have no list-style (to hide the bullet points) set the text size. The next rule is the most complex this is for the li elements (you will notice that I’m using child selectors in my css like the .tabs > ul > li instead of just .tabs ul li this is because I read a document from Mozilla saying that CSS is read right to left instead of left to right so if you specify that the tag is a direct child the css perfoms slightly better. Writing Efficient CSS there are lots of other goodies in there to get your head around (I’m not there yet with it all but I’m getting there).

Ok stop interupting me!! So i set the display:block and float:left to get them to display correctly (I could use display:inline but I just prefer this method). The user-select:none rule (-moz and -webkit are just browser specific variations) makes it so that when you click the text you don’t move the cursor to that part of the page. Then we have the border-radius rules which say we have two curved edges at the top and two straight corners at the bottom. The final part to this is the gradient. Instead of using images (which means more syntax if to want expandable tabs) I’m using CSS3 gradients. I use this great tool Ultimate CSS Gradient Generator which helps you create the gradients visually then copy the code into your css. I’ve deleted the IE specific stuff because the javascript on this technique only works on IE8 and above so IE users will just get what they get. All the other rules in the css use variations of what I just explained. The only other thing to note is that the pseudo class of hover has the same rules as the activeTabHeader which is the style added to the active tab, so when you hover the tab that you are over will display the same as the active tab.

The Pseudo Code

when page loads
  get tab container
  set current tab with class of activetabheader and store which tab we are on
  hide two tab pages we don't need

  on click of one of tabs
  remove class of activetabheader and hide old contents
  add class of activetabheader to new active tab and show contents

So hopefully the pseudo code javascript looks pretty straight forward, on page load we want to get the tab container, set the current active tab and hide the two tab pages we don’t need yet. The we also want to know which tab is clicked and change everything accordingly.

The Javascript

window.onload=function() {

  // get tab container
  var container = document.getElementById("tabContainer");
    // set current tab
    var navitem = container.querySelector(".tabs ul li");
    //store which tab we are on
    var ident = navitem.id.split("_")[1];
    navitem.parentNode.setAttribute("data-current",ident);
    //set current tab with class of activetabheader
    navitem.setAttribute("class","tabActiveHeader");

    //hide two tab contents we don't need
    var pages = container.querySelectorAll(".tabpage");
    for (var i = 1; i < pages.length; i++) {
      pages[i].style.display="none";
    }

    //this adds click event to tabs
    var tabs = container.querySelectorAll(".tabs ul li");
    for (var i = 0; i < tabs.length; i++) {
      tabs[i].onclick=displayPage;
    }
}

// on click of one of tabs
function displayPage() {
  var current = this.parentNode.getAttribute("data-current");
  //remove class of activetabheader and hide old contents
  document.getElementById("tabHeader_" + current).removeAttribute("class");
  document.getElementById("tabpage_" + current).style.display="none";

  var ident = this.id.split("_")[1];
  //add class of activetabheader to new active tab and show contents
  this.setAttribute("class","tabActiveHeader");
  document.getElementById("tabpage_" + ident).style.display="block";
  this.parentNode.setAttribute("data-current",ident);
}

So the first function fires on window load. Get the tabContainer div and then query the this container for all the li elements. Next we get the first id and split it where the underscore(_) is and just keep the number (in this case 1). Then we get the li items parent node (ul) and add the HTML5 attribute data-current to it and give it the value of the ident variable(which is 1) this is how we track which tab we are on. Now we give the li the calss of activeTabHeader. The next part puts all the divs with a class of .tabpage in an array and then apart from the first one it adds display:none to the css. (We skip the first one in the array by setting the i variable to 1 instead of the usual 0). then we add a click event to all the tabs so that when they are clicked the displayPage function is called.

The function displayPage then hides the current page and removes the class activeTabHeader from the active tab and adds the class to the tab that has been clicked and changes the css to display:block for the new page.

Thats it all done. Next time we will create a jQuery plugin so we can call this functionality simply on any correctly created tabContainer. We will also give the option of 3 different UI styles.

View DemoDownload Source

102 thoughts on “Pure Javascript Tabs with HTML 5 and CSS3

  1. Munyoki

    Just implemented this on a rather large project I’m working on. After doing a little bit of tweeking on the CSS, i got it to look just right. Excellent work!

    Reply
    1. Matt Walker Post author

      Thanks a lot. Glad to be of help.

      Reply
  2. TheNewGuy

    While going through this article I noticed that you are setting the z-index on the tabs but yet I don’t see any place where you set positioning to something other than the default static positioning. According the specification found here:

    http://www.w3schools.com/css/pr_pos_z-index.asp

    z-index only works with elements that use fixed, absolute or relative positioning. So I’m not entirely sure your z-index is doing anything at all.

    That being said I could be missing something, after all I’m kind of just the new guy here.

    Reply
    1. Matt Walker Post author

      You’re absolutely right. The z-index was doing nothing. When I originally wrote the CSS I was going to have the tabs and content absolutely positioned but I changed my mind. The z-index was left over from there and I forgot that I’d changed it when I wrote the post.
      I’ll amend the post and all the source and demo files.
      Thanks for telling me. If you spot any more errors be sure to get in touch!!

      Reply
  3. Matt

    I’m trying to implement this code, but the page is not hiding all of the tabpages (except the 1st) when I initially load the page. Thoughts?

    Reply
    1. Matt Walker Post author

      Could you send me what you have done and I’ll check it through for you?

      Reply
  4. VeryThorough

    Thanks for this script. It’s so beautifully concise!

    One quick note–there seems to be an extra line (#7) dropped into the javascript code box in the article. Threw me for a loop when I kept getting alert boxes! (Yes, I’m a bit new to this….)

    It’s not in the demo or download source, so if I had copied from there, I’d have saved myself some trouble, but I thought I’d pass the info along in case others make my mistake.

    Also, I had a question about “.querySelector”, which I learned doesn’t work in IE7 and below. It makes sense that you use it, since you’re gearing towards newer browsers anyway, and it certainly simplifies the code. However, I’d like to increase my compatibility. I know it won’t be as elegant, but could you give me some clues as to how I could make this work without querySelector?

    Thanks again!

    Reply
    1. Matt Walker Post author

      Hi there.
      Thanks for the great comments.
      I’ve re-written the code so it will work in legacy browsers.The css needs looking at especially for IE6 but the javascript works.

      Heres the file LegacyTabs

      Hope it helps.

      Reply
  5. Martin

    problem is that JS remove ALL content that is wrapped in DIV, also broke my other JS (galleryffic)

    Reply
    1. Matt Walker Post author

      Hi Martin
      Could you send me the code and I’ll have a look at it for you?
      Cheers

      Reply
  6. Martin

    The main problem was in double onLoad calls, which I fixed, another problem is, that:
    //hide two tab contents we don’t need
    var pages = tabcon.getElementsByTagName(“div”);
    remove all div in code, which will screw my formating. Not sure whoat is this code good for anyway, I change it to:
    var pages = tabcon.getElementsByClassName(“tabpage”);
    but this doesnt work in IE7

    Reply
    1. Matt Walker Post author

      Hi Martin glad you sorted the onLoad calls.

      The line:
      var pages = tabcon.getElementsByTagName(“div”);
      puts all the div elements within the tabscontent div into an array that you then can call later.
      The reason I used this method is because getElementsByClassName doesn’t work in IE6-8.
      So i don’t really know what you mean by this comment.

      As for the rewrite. I’ve written a plugin for jQuery. Here: jQuery Tabs

      Reply
    1. Matt Walker Post author

      Hi Jessica

      Sorry for the late reply. Have you got a page link so I can look at the code?

      Matt

      Reply
  7. Gily

    Hi Matt,

    I’m trying to get the text in the main content area formatted into two columns, but I’m having trouble achieving that. I’m trying to work w/ divs styles via CSS. Any ideas how to do it?

    Thanks!

    Gily

    Reply
    1. Matt Walker Post author

      Hi Gily

      Put 2 div’s in the tabpage div. Then style as follows:

      #divLeft { width:320px; float: left;}
      #divRight { width:320px; float: right;}

      Then add the following to the styles for the outer div the tabpage:
      overflow:auto;

      That should work fin. Any issues get back to me or give me a link to the code.

      Cheers

      Matt

      Reply
  8. Gily

    Thanks a lot for your prompt reply, Matt. Your solution works great – I had missed the overflow thing…

    Gily

    Reply
  9. Seth

    hey matt. nice job…

    would it be possible to target one of these created tabs to open from another page? i’m using a similar system now but can’t seem to nail down how to open a specified tab on “page load”

    many thanks in advance…
    seth

    Reply
  10. clara

    hi,

    i’ve got total of 31 tabs(each calendar day) and wanted to put the navigation button like in excel. could you please kindly give us some examples?
    i’ve been looking for the solution for a while :(

    Reply
  11. Isac

    Hi Matt -
    I have ben looking for something like you have here and wish to talk to you
    please e mail me back
    Thanks

    Reply
  12. Keith

    Hi Matt,

    I was playing around with your tutorial and I noticed something strange. I added an extra tab so that I would have 4 total. I added the frame with a new div like this:

    After this, I noticed that when I tried to add images in to the tab content section in the 2nd and 3rd tabs, they didn’t stay within the frame. In the 1st and 4th tab, images stayed within the frame. I’ve been playing around with the images and it’s specifically in the 2nd and 3rd tabs that the image pops out of the frame. I’m guessing it’s something in the java script?

    If you or anyone else on here can help me with this issue, please let me know.

    Thanks!

    Reply
  13. sulong

    Thank you for the code, i’m using it in my website, but my issue here is the same as issue submitted by seth, which how set a specified tabs when the page load.

    thank you,

    Reply
  14. Metin Lapo

    this is the best pure tabbed view i’ve seen

    is it possible to add back button funtionality

    thx in advance

    Reply
  15. Jake

    Great method! Any way to add an easing affect to this? Would make this perfect!

    Thanks!

    Reply
  16. Jake

    Also how can you make it so tab number 2 is active on load instead of tab 1?

    Thank you!

    Reply
  17. Jake

    Figured out the active tab question.

    on this line of code add the ID name of the active tab you want after the li:
    var navitem = container.querySelector(“.tabs ul li#tabHeader_2″);

    Still searching for a way to have an easing effect on the div transitions.
    Help please!??

    Reply
  18. dev

    I want to use this code in my WordPress site on Contact Us page… How can I use this code there.. Help

    Reply
  19. Jake

    Figured out the fade in of the div

    (function ($) {

    $.fn.acidTabs = function (options) {
    options = $.extend(options);
    return this.each(function () {
    var o = options;
    container = this;
    container.setAttribute(“class”, o.style);
    var navitem = container.querySelector(“li”);
    //store which tab we are on
    var ident = navitem.id.split(“_”)[1];
    navitem.parentNode.setAttribute(“data-current”, ident);
    //set current tab with class of activetabheader
    navitem.setAttribute(“class”, “tabActiveHeader”);

    //hide two tab contents we don’t need
    var pages = container.querySelectorAll(“.tabpage”);
    for (var i = 1; i < pages.length; i++) {
    pages[i].style.display = "none";

    }

    //this adds click event to tabs
    var tabs = container.querySelectorAll("li");
    for (var i = 0; i < tabs.length; i++) {
    tabs[i].onclick = displayPage;

    }

    });

    // on click of one of tabs
    function displayPage() {

    var current = this.parentNode.getAttribute("data-current");
    //remove class of activetabheader and hide old contents
    $('#tabHeader_' + current).removeClass('tabActiveHeader');
    $('#tabpage_' + current).hide();

    var ident = this.id.split("_")[1];
    //add class of activetabheader to new active tab and show contents
    $(this).addClass("tabActiveHeader");
    $('#tabpage_' + ident).fadeIn('fast');
    this.parentNode.setAttribute("data-current", ident);

    }

    };

    })(jQuery);

    Reply
  20. Kelly

    Hiya, I’m trying to make this work in IE7 and have used the legacy tabs solution however there’s a problem with the javascript and it hides everything on page load so none of my tabs show. Can you help?

    Reply
  21. Mark

    Hi Matt or a CSS guru;

    I’ve a problem which seems to occur when I place the tabs in the sidebar of a WordPress theme I’m developing. When I set the width of tabContainer to 300px in the demo, everything resizes fine. However, when I float it within a div in the sidebar, the tabs indent about 30px and I can’t get them to align to the left of the .tabscontent box.

    Would appreciate any guidance.

    Thanks.

    Reply
  22. Yusuf

    hi,thanks for the info , one thing i noticed is the tabs are not reset perfectly if you check with different browsers like firefox and ie the tabs drop about 2 px.

    Reply
  23. Alam Shaikh

    hi…….
    I have problem in ie7,ie8 this tabs not working..
    plz give me suggestion, what should i do ?

    Thanks a lot.

    Reply
  24. Sammy

    Hey Matt!
    Great Work! I would love to use it on my website. Is there a way i can include multiple Containers with Tabs on one page?

    Thanks alot!

    Reply
  25. Pingback: Types of Biryani | Hyderabad Catering Services – Company – Lajawab Caterers

  26. Angela Speed

    Great piece of code and very concise instructions for us novices.

    I was able to change almost everything to create what I need, except a couple things:
    1. is there a way to change the tab width with a percentage so it re-sizes the tabs based on the number of tabs to fill the horizontal space minus the padding in between?
    2. besides using code like WEEK 1 to select the current tab linked from an email, is there a way to dynamically make the current week the current tab?
    THANKS FOR ANY HELP.

    Reply
  27. ryaz

    is it possible by click submit button and it leads to the corresponding nearer tab?

    Reply
  28. Rick

    I’m builidng a new page and using this, which is fantastic. Works great in Chrome and Firefox, but the .js is not working in IE8 (getting this error:
    Webpage error details

    User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; GTB7.3; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; MS-RTC LM 8)
    Timestamp: Mon, 13 Aug 2012 00:54:50 UTC

    Message: Object doesn’t support this property or method
    Line: 7
    Char: 5
    Code: 0
    URI: http://www.playhouseonpark.org/js/tabs.js

    Here is a sample page:
    http://www.playhouseonpark.org/pop/20122013Season/mainstageseries_miceandmen.html

    It looks great in the other two browsers, so I’m hoping maybe it’s an easy tweak to get it to work in IE, because this is exactly what I was looking for. Thanks!! Rick

    Reply
  29. Edd

    I’m so glad I found your blog, I’ve been scratching my head about a lot things, but a couple of hours spent here at work (time well spent) and I feel like I completely get HTML5 now. Can’t wait to get home and put it into practice.

    One question: Is it at all possible to create a link in tab 3 to go to an anchor in tab 2, without refreshing the page?

    Okay one more question: is it possible to link to the page from somewhere else, and open tab 2 by default?
    (I think Seth and Jake asked this question earlier, and nearly sussed it, but not quite).

    Thanks

    Reply
  30. Rachit

    $(‘#tabs li’).click( function ( ) {
    $(‘#tabs li’).addClass(‘unactivetab’);
    $(this).removeClass(‘unactivetab’);
    $(this).addClass(‘activetab’);
    $panel = $(this).children(‘a’).attr(‘href’);
    $(‘#tab-contents div’).addClass(‘unactivepanel’);
    $($panel).removeClass(‘unactivepanel’);
    $($panel).addClass(‘activepanel’);
    } );
    how is this code for switching tabs ?

    Reply
  31. Prashant

    Hi,

    I am trying to use this code for my blog.

    But I am not getting proper result.

    Result showing tabs but they are not clickable and all content is reflecting on first tab.

    Please help me to get it fix.

    Thanks

    Reply
  32. Harley

    Thanks for the fantastic template for HMTL 5 Tabs. It is 90% better than the DekiScript Tabs I was working on.

    Thank you once again. :)

    Reply
  33. Hema

    Hi Matt,

    can you give me some ideas on how to implement sub tabs.

    Thanks in advance

    Reply
  34. efren rodriguez

    Hi,

    I am using your code and works very good for Firefox (16.01) also when I copied to the server and test the site works OK, but for IE 8 and IE9 the screen is complete in black and the tabs not work.

    So I have tested the demos and Works for this kind of IE versions, I could not find the problem.

    Some suggestions to fix this.

    Reply
  35. Pingback: Tabs « Dev 'o Web

  36. Jitendra Modi

    Awesome tutorial , great work.
    I implement your tab code in one of my website but i am getting one problem. you provided main tree tabs as follow

    now whenever i m write another div tag inside your “tabpage” div it get disappear.

    please suggest some solution as early as possible.

    Reply
  37. zakyiah

    hello,

    thanks for amazing tabs, but i have some issue when i put content of tabs and make zoom the ccontent appear out div .

    i put all div-width : auto

    Reply
  38. Jimmy Zubik

    i’m trying to implement this on a bigcommerce site, but the content loads then disappears. the js is some how blocking content that should be shown, know of any way I could trouble shoot this? Thanks!

    Reply
  39. zakyiah

    thanks for amazing code ..i relly like it but i have issue
    when i put the code on my page it,s ok but when i meak zoom in the content of tab be out side the div..and the pic &font zise be bigger i wont it the fixed
    i hope there is soulotion for that
    thanks agine

    Reply
  40. Charlie

    I’ve been playing around with these tabs, and they’re pretty snappy. I’d like to put canvas objects *inside* the tabs (on a tab?), but I’m finding that the objects won’t display. Does anyone have any insight into why not, or what I can do to make it work?

    Reply
  41. Pingback: html tabs doesn’t work any more video

  42. willy

    I try include a form in each tab content you create, matt. But every time i submit a form (example i submit form in tab 2), it always goes back to tab 1 and tab 1 content. how to make it stay in current submitted form tab?

    Help me anyone…?

    Reply
  43. Rob

    Anyone know how to display the content on hover rather than on click? I tried changing onclick=displayPage to onMouseOver=displayPage, but no luck. Seems like that should work though…

    Reply
  44. FM

    hi Matt,

    Possible to clarify the code below a bit further. I’m kinda lost – Wanted to create two columns.

    Put 2 div’s in the tabpage div. Then style as follows:

    #divLeft { width:320px; float: left;}
    #divRight { width:320px; float: right;}

    Then add the following to the styles for the outer div the tabpage:
    overflow:auto;

    Thanks,
    FM

    Reply
  45. Craig

    Thanks for this! It is brilliant.

    Just one thing I have noticed and I am not sure if it is just mine but while the page is loading all the content from all the tabs is displayed on the page until the page finishes loading, then it get hidden.

    Is there a solution to this?

    Thanks!

    Reply
  46. Kevin Limpens

    Hello,

    I used your script for my website, but when I try it in IE9 the tab menu doesnt work.

    Can you please help me and tell me what I did wrong?

    Tanks,

    Kevin

    Reply
  47. Pingback: CSS3 help adding a background to html page | BlogoSfera

  48. koren

    Hey, tried this code and for some reason it doesn’t work at all in IE fine in all other browsers. Any ideas

    Reply
  49. Fred

    Hi, help me please

    how could select the 3 tab

    loading the page instead of 1 tab

    Reply
  50. Adedeji Adedayu

    Hello,

    Work great with me. but i noticed that whenever i open my webpage, it leaves an extra space at the bottom of the page and also it doesnt seem to work in IE. please i need help here. Thanks

    Reply
  51. replyBack

    Did not worked for the IE10 using JavaScript, HTML5. Works on the Firefox, Chrome without issues. Please suggest

    Reply
  52. Stuart

    Hey Matt,

    Solid tutorial and a simple and effect tab solution, well done!

    Just wanted to know if there was an easy way to have a different tab. i.e. three tabs with forms and if one form is complete then it redirects back to the tab page but the tab the form was on is displayed rather than just the first tab.

    Thanks in advance and keep up the good work.

    Reply
  53. Stuart

    Got valuable assistance from my best bud Dave to solve the issue of calling different tabs via the URL.

    Using the code below, you can now have http://www.yoururl.com#tab=x where x is the tab number you want to call.

    Code is:

    window.onload=function() {

    // get tab container
    var container = document.getElementById(“tabContainer”);
    var tabcon = document.getElementById(“tabscontent”);
    //alert(tabcon.childNodes.item(1));
    // set current tab
    var navitem = document.getElementById(“tabHeader_1″);

    //store which tab we are on
    var ident = navitem.id.split(“_”)[1];
    //alert(ident);
    navitem.parentNode.setAttribute(“data-current”,ident);
    //set current tab with class of activetabheader
    navitem.setAttribute(“class”,”tabActiveHeader”);

    //hide two tab contents we don’t need
    var pages = tabcon.getElementsByTagName(“div”);
    for (var i = 1; i < pages.length; i++) {
    pages.item(i).style.display="none";
    };

    //this adds click event to tabs
    var tabs = container.getElementsByTagName("li");
    for (var i = 0; i < tabs.length; i++) {
    tabs[i].onclick=displayPage;
    }

    //ignore hash variables that are null or empty
    if (window.location.hash !== null && window.location.hash !== '' && window.location.hash !== '#') {
    //split by parameters
    var hashparam = window.location.hash.substring(1).split("&");
    for (var i = 0; i 0 && parseInt(param[1]) <= tabs.length) {
    //we have the right tab, call the click method on it
    tabs[parseInt(param[1]) – 1].click();
    }
    }
    }
    }

    // on click of one of tabs
    function displayPage() {
    var current = this.parentNode.getAttribute("data-current");
    //remove class of activetabheader and hide old contents
    document.getElementById("tabHeader_" + current).removeAttribute("class");
    document.getElementById("tabpage_" + current).style.display="none";

    var ident = this.id.split("_")[1];
    //add class of activetabheader to new active tab and show contents
    this.setAttribute("class","tabActiveHeader");
    document.getElementById("tabpage_" + ident).style.display="block";
    this.parentNode.setAttribute("data-current",ident);
    }

    Reply
  54. Dan

    Hi! Awesome work! Just used this in a project of mine. IE has some unhappiness with the css, but chrome works great!

    Beautifully written, well done! Thank you.

    Reply
  55. Tan Nguyen

    Error if i used “<div" for content in one of tabcontent. it hide my "<div"…..

    Repair below……
    ————————————————–
    //hide two tab contents we don't need
    var pages = tabcon.getElementsByTagName("div");
    for (var i = 1; i

    //hide two tab contents we don’t need
    var pages = tabcon.getElementsByTagName(“div”);
    for (var i = 1; i =0 ) {
    pages.item(i).style.display=”none”;
    }
    };

    Reply
  56. Greg Pechauer

    Great tab design and code! I’m currently using the js script. When one first views my clients website and drills down under the “Products” tab to “Watering” and then one of the available “links”—Gas, Electric, etc.; the page includes your Tabs. It works beautifully, however, their is about a 1/3 to 1/2 second delay prior to the initial tabs “snapping closed.” Is their a bit of code to be added that starts the tab in “full-closed” position? The brief, but noticeable loading mechanics was caught by my client. Of course, once it’s in the browser’s memory, it works with no hesitation. Thanks for your reply. Greg

    Reply
  57. shane

    Matt, How do I make this work if I wanted the tabs to be on the left as a vertical tabbed menu?

    Reply
  58. Norma

    You are my life saver!! I’m tweaking the CSS, but this has seriously saved my hours of stress. Originally I was using jQuery to create something similar, but kept glitching. Thank you

    Reply
  59. bala

    I’m a beginner..
    can u pls help me to increase the size of the entire tabbed element??
    Thanks in advance..

    Reply
  60. Pingback: Pure Javascript Tabs with HTML 5 and CSS3 | BestCodingTutorials

  61. Kleag

    Hi Matt,

    Very useful and interesting. Now that I understand it I could reproduce your ideas but I would gain time if I could reuse your code at work directly. Unfortunately you don’t indicate a licence so it is not authorized, neither for proprietary software nor free one.

    I am a free software developer and thus I find very important to respect the copyright holder and the freedom he is willing to give. Could you please indicate somewhere the license you intend to give to us ? A BSD one would seem good if you want to allow us to do whatever we want with your code.

    Thanks again.

    Reply
  62. David

    Matt,
    I’m using this code in my mobile apps editor. I was looking for a quick simple way to add sub nav without getting into my code. Works great on the first webpage I create. When creating page two, page one stops working. Is this a function of my wysiwyg (CKeditor) or am I missing something?

    Reply
  63. Vertika

    Hi

    I am unable to display any div tags in the tabContent. Simple code which I did is given below…..but doesnt show divs. Can you please help?

    Pure Javascript, HTML 5 & CSS3 Tabs

    Page 1
    Page 2
    Page 3

    Hello
    Page 1
    Without DIV

    Page 2
    WITHOUT DIV WORKS FINE

    Page 3
    WITHOUT DIV WORKS FINE

    Back to Tutorial

    var _gaq = _gaq || [];
    _gaq.push(['_setAccount', 'UA-1332079-8']);
    _gaq.push(['_trackPageview']);

    (function() {
    var ga = document.createElement(‘script’); ga.type = ‘text/javascript’; ga.async = true;
    ga.src = (‘https:’ == document.location.protocol ? ‘https://ssl’ : ‘http://www’) + ‘.google-analytics.com/ga.js’;
    var s = document.getElementsByTagName(‘script’)[0]; s.parentNode.insertBefore(ga, s);
    })();

    Reply
  64. Vertika

    The page layout was displayed in my earlier mail instead of the code. The word ‘Hello’ is appearing here but not in the tab layout as it is in DIV. Please let me know an email id where I can post the code.

    Reply

Leave a Reply

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