June 10, 2016
A couple of weeks ago, I needed to create a tabbed content area to organize the various search fieldsets on a mock travel site. With extensive Google search and some help from my instructor Ryan, I arrived at a very simple yet elegant solution that involves radio buttons, some clever CSS and a couple of lines of jQuery.
The HTML Markup:
First I created a set of radio buttons with labels. I connected the inputs and their labels with their id attributes so that clicking on the label would select the corresponding radio button. This is important because we’ll be hiding the input fields and we want the users to be able to make a selection by clicking the labels.
The label element also holds a data-* attribute which stores the unique class name of the section of information we want to display when that tab is clicked.
Next, I created separate sections that hold the contents for each tab and I gave each section two class names. The first “packages” is a general class name which applies to all the sections (this will help with styling and jQuery) and the second one is a unique class name which is exactly the same as its corresponding label’s
I used the CSS to set all
display:none and then I used the adjacent sibling combinator to style the label for the radio input that was checked.
input:checked + label.
I also set all the sections with the class of “packages” to
display:hidden and then used the
:first-of-type pseudo-class to
display:block so that the user can only see the first section when they land on the page.
First, we drop the link to the jQuery cdn at the bottom of our HTML page right before we close the
body tag in a set of
script tags. Then we open a new script to write our jQuery. Then we write the
$(document).ready(); function which tells the script to wait for the document to finish loading before firing off the function(s) we want it to run.
Inside the document ready, we define an event listener. So when $(‘.search label’) is clicked, we tell it to find the
.data() attribute of the label that is clicked and store it in a variable called
$selection. Then we ask it to hide the section with class of packages and show only the section that has the same class name as the as the
data-* of the selection we made.
Here we can see why making the
data-* attribute the same as the unique class name of the section we want to display really helps us. All we had to do in the jQuery was to store the
data-* information in a variable and concatenate a
'.' before it to turn it into the class name.
Finally, here’s what it looks like when we put it all together.
Thanks for checking out my simple tabbed content tutorial! It’s very customizable, so just copy the code, drop it into your projects and make all the changes you need. Feel free to send me your suggestions or ask questions in the comments below.