How to Create Expandable Sections Within a Web Page

by Antoinette Smith

Expandable sections often appear on Web pages as menus or blog snippets. These expandable sections can be created using JavaScript and CSS properties. With a little HTML knowledge, you can create expandable sections within a Web page.

1

Enclose the section you want to expand in <div> tags. Place a <div> tag before the expandable area and a </div> tag at the end of the area. The <div> tags are similar to the <html> and <body> tags. They divide an HTML document into sections, but do not add formatting.

2

Give your <div> an ID and a style. Change your opening <div> tag to <div id="expandable" style="overflow:hidden;display:none;">. This style hides or collapses your content by default. Overflow and display are the style properties. The overflow property is set to hidden to hide any content larger than the content area's size. The display property is set to none to prevent content within the <div> tags from being displayed in a Web browser.

3

Enter the following just before the </div> tag:

<a href="javascript:Tog('none')">Less</a>.

This line makes your content collapse if it has been expanded. Specifically, it calls a JavaScript function, Tog. This call to Tog dynamically sets the display property to none.

4

Enter the following just after the </div> tag:

<a href="javascript:Tog('block')">More</a>.

This line makes your content expand. This call to Tog dynamically sets the display property to block. Setting the display to block makes the content appear with line breaks above and below it.

5

Enter the following within the <head> tags of the HTML document where the expandable content will appear to begin the section of JavaScript:

<script language="JavaScript" type="text/javascript">

6

Type the following to define the Tog function that is called by the expandable section:

<!--function Tog(x)

The 'x' within the Tog(x) is a dummy variable that takes the value of the display property to apply to the section.

7

Type the following:

{ var expandable = document.getElementById('expandable');

The getElementById determines the section the function affects. In this case, it is the <div> with an ID of expandable.

8

Type the following to set the section's display property to the value of x:

expandable.style.display = x} // -->

9

Type the following to end the section of JavaScript:

</script>

References

About the Author

Since 2008, Antoinette Smith has covered sports and local events for "TechNews," the student newspaper for the Illinois Institute of Technology. She holds a Bachelor of Science in professional and technical communication from the Illinois Institute of Technology.

Photo Credits

  • photo_camera Hemera Technologies/AbleStock.com/Getty Images