Tag Archives: preventDefault

Episode 4: jQuery tabs without a plugin

jQuery Tabs without a plugin!

There are piles of jQuery tabs plugins out there, but creating tabs is not very complicated at all. In this video, I’ll step you through creating simple tabs with just a few lines of code.

We’ll create a page featuring the six noble gases with a bit of information about each one. We’ll pull a bit of information from Wikipedia for each gas.

We get started by setting up our HTML – first we create the content for each tab section, giving each section of content a unique ID so that we can easily reference it later. Note that we use semantic names for those ID’s related to the information contained inside rather than just numbering the sections – that means it’s super easy for us to re-arrange the order of our content as needed without having to worry about re-naming.

Then we create the tabs themselves – which is as simple as an unordered list with anchor links to the sections of content we created. We style that up with just a few lines of CSS to make the list of links look like tabs and to add a background color and border to each section of content. We’ll cover a quick trick for improving the usability of your tabs which will also help you with all sorts of navigation, buttons, and more.

Once we’ve got all of that out the way, we’ll jump into JavaScript. First, we hide all the content sections. Then, we write the magical code that will make the tabs work as expected. While we’re doing that, we learn about hashes and do a quick lesson on how to move around an HTML document. We also learn about how we can interrupt the browser and prevent its default behavior when we need to.

Next, we take a look at how to highlight the currently selected tab by adding and removing a CSS class. Finally, we add just a bit of code to show the first content section when the page is first loaded.

Before we wrap up, we’ll quickly cover caching selectors to help your code run a bit faster. Little improvements make a big difference once you start writing more complex JavaScript, so it’s a good idea to learn optimization early! Make it a habit to watch out for any time you’re using the same jQuery selector more than once in your code.