Creating tabs in HTML + CSS + JS

tabsIn previous posts we looked at how JavaScript can interact with HTML using:

  • Event Handlers in HTML such as onClick, onFocus, onBlur…
  • the DOM (Document Object Model) to access HTML objects using: document.getElementById(“objectId”)

CSS is applied to HTML objects. Using JavaScript you can change the CSS attributes of all your HTML objects using:

  • document.getElementById(“objectID”).style

For instance:

  • document.getElementById(“myTextBox”).style.background=”#FF0000″;
  • document.getElementById(“myHeading”).style.padding=”25px”;
  • document.getElementById(“myDiv”).style.display=”none”;  //This will make the DIV tag invisible
  • document.getElementById(“myDiv”).style.display=”block”;  //This will make the DIV tag visible

Let’s combine all these techniques to create some tabs:

The HTML code is fairly straightforward: Each tab needs a DIV tag for the tab itself and a DIV tag for its content:

<div id="tab1" onClick="JavaScript:selectTab(1);">Tab 1</div>
<div id="tab2" onClick="JavaScript:selectTab(2);">Tab 2</div>
<div id="tab3" onClick="JavaScript:selectTab(3);">Tab 3</div>

<br/>

<div id="tab1Content">
  This is the content to display in the first tab.
</div>
<div id="tab2Content">
  Welcome to tab 2!
</div>
<div id="tab3Content">
  Tab 3 is probably the best of the three tabs.
</div>

Then CSS code can be used to customise the look and feel of the tabs (Background colours, borders, padding…)
But mainly CSS is used to only display the first tab’s content area and hide the other two. This is done using the display attribute in CSS:

#tab1Content {
 display: block; 
}

#tab2Content, #tab3Content {
 display: none; 
}

Finaly the JavaScript code is used to handle the onClick event triggered by the tabs.
It accesses the style attribute of each tab’s content area to eithe hide or display the content of the tab based on which tab has been clicked.

function selectTab(tabIndex) {
  //Hide All Tabs
  document.getElementById('tab1Content').style.display="none";
  document.getElementById('tab2Content').style.display="none";
  document.getElementById('tab3Content').style.display="none";
  
  //Show the Selected Tab
  document.getElementById('tab' + tabIndex + 'Content').style.display="block";  
}

Let’s see all this code in action:

See the Pen Tabs using HTML + CSS + JavaScript by 101 Computing (@101Computing) on CodePen.

Your Challenge


Tweak this code (click on the “edit on CodePen” logo) to add an extra tab (Tab 4) to this script.
You will need to tweak the HTML code first, then the CSS then the JavaScript.

Extension Task:


Change the background of your tabs using a gradient. To do so you can use this CSS gradient generator.

gradients

Did you like this challenge?

Click on a star to rate it!

Average rating 3.8 / 5. Vote count: 5

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!