<< Back

Implementing site tabs in JS

What if you have multiple sections on your site but you also want to keep it looking tidy and compact? Tabs are a great solution.

You have some options to choose from when it comes to implementation though, for example you could use the radio element in conjunction with CSS to achieve roughly the same effect. But in this article we will be focusing on a JS solution.

We will be using jQuery to help, and we'll also implement a simple feature to make our tabs more robust.

Here's what we have to do:

  1. As you've read above, we'll need jQuery. Go get it added.
  2. Decide what elements you want to be using for tab buttons and tab containers. It doesn't really matter but I recommend li, a and div respectively.
  3. Create your buttons and add the required classes. The one that is enabled by default should have an active class:

    Don't be scared of all the data properties, those are really helpful!
  4. Add your tab containers, and give them the appropriate classes too: On any page you want to show the magic, include your file like so:

    Hint Make sure that each container has a matching class to the one in the button assigned to it! For example, page 1 button has a data-target property .tab_page_1 - that is the class you should add to the tab that it opens!
  5. And now for the JS part of it all, add the following code to your script tag:

    Hint Does this code look familiar? This is the same code that lies at the base of our pagination script! If you already have the code from the pagination article, you don't need to add this, you already have tabs enabled!

And this is it! I know it looks a little verbose, but that is only due to the data attributes. But those same attributes let us separate our tabs into groups! If you wanted to have more than 1 set of tabs, simply change the data-group value on the next set of tabs and they will all work independently!

Those same attributes also let us place our tab buttons anywhere on the site since they don't use relative querying! That means you can have a tab button in the header and a tab button in the footer but they will work together! This lets us do some interesting stuff, like pagination for example.

I hope this article was of use! It may be a little confusing, so don't hesitate to ask me anything! I'll be glad to help you or to fix some errors on my page! Thank you for reading.