How to Show and Hide Divs with JavaScript

Let’s say that you want to make a tabbed menu. Maybe you want to create a webpage where a user can click a link (or a div, or span, whatever you want) and content on the page changes. One way that this can be done is through a DIV and JavaScript. Basically, we’re going to have DIVs hold our content, and JavaScript is going to allow them to display and disappear on the page at the user’s request.

To start, we’re going to need to set up DIVs to hold our content. To avoid over complicating things, we’re going to give them numeric IDs, starting with 1 and (in this tutorial) ending with 10. Basically, these are going to act as containers of sorts, and we’re going swap them out on a page using JavaScript.

Our Divs.

All ten of our DIVs. Don’t forget the numeric ID!

Now, we’re going to set up the loop that causes all of the DIVs to disappear and then displays the one that the user wants. For this, we’re going to use a JavaScript function, declared in the HEAD of our page.

For Loop

Our for loop.

Basically, this loop is composed of a function, “hideDivs” with a variable “showMe” passed into it (That’s only important later.) The for part basically states that the code should execute ten times, and modify the element with the ID “i” (The DIVs increasing in order) The modification in question is to set the display type to “none”.

This is where “showMe” comes into play. The for loop hides all of our DIVs, so we need to tell the function to set the DIV we pass to it to be viewable by setting its display type to “block”. Where do we tell the function what the variable showMe is? In the function call in our clickable SPAN! (That’s what I used, anyway.)

Our spans with function call.

Our spans with the function call.

These SPANs sort of function as links, with an onClick statement and the number of the DIV that it “links” to. That number in parenthesis is what gets passed to the function we created earlier, and its purpose is to tell that function to set the display type to “block” for the number of the DIV we’re linking to.

And there you have it, a quick and easy way to swap out DIVs on a webpage with JavaScript and a for loop!

–Ryan Craig


~ by ryanwcraig on September 17, 2012.

%d bloggers like this: