Creating tabs in HTML + CSS + JS

In 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:

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:

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.

Let’s see all this code in action:

See the Pen DHTML Tabs 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

Share Button
Posted in Computer Science, JavaScript

Our Latest Book

Follow this blog