How to Expand & Collapse a DIV in JavaScript

By Kevin Lee

Divs allow you to group elements on a Web page. There are two ways to cause divs on a Web page to disappear. First, you a code makes a div into an invisible element, or you can use collapse. If you simply make a div invisible, an empty space remains where the div exists. Collapsing a div removes that empty space leaving no "hole" in your Web page. Using JavaScript linked to a button, you create your own divs that collapse and expand when users click the button.

Add Div to Web Page

Step 1

Launch Notepad and open any of your HTML documents.

Step 2

Add this block of HTML code to the document's "body" section:

Div text

This code creates a div and a button. The div contains a paragraph with text that reads: "Div text." Replace that text with anything you like. The "button" calls a JavaScript function when clicked. That function causes the div to switch between a collapsed state and an expanded state.

Step 3

Locate the "id" and "class" properties in the div tag. To create an expanding and collapsing div, you must give the div an id value. In this example, that value is "MyDiv." The div also has a class property. In this instance, that property's value is "divVisible." That is the name of a CSS class defined in the next section.

Add CSS Classes and JavaScript

Step 1

Add the following CSS code to the document's "head" section:

This creates the "divVisible" class and another class named "divHidden." The "divVisible" class sets its display value to "block." The "block" value makes any HTML element that references the class visible and expands it to occupy space on the Web page. The "divHidden" class sets its display value to "none." Any HTML element referencing that class collapses and leaves no space behind.

Step 2

Add this JavaScript code below the CSS code:

The divID variable holds the id value of the div you wish to collapse and expand. That value is "MyDiv." The rest of the code obtains the div's current CSS class name and switches it every time the code runs. The first time the code executes, it changes the div's class name to "divHidden." The second time it runs, it changes the class name back to "divVisible."

Step 3

Save the HTML document, and open it in your browser. The paragraph containing your paragraph appears.

Step 4

Click the "Collapse/Expand" button. The text collapses. Click the button again to expand the text. Note how the button and other elements below the text move up when the text collapses and move down when the text expands.

×