iNET Interactive - Online Advertising Agency
          
   Home    Authors    About    Login    Contact Us
   Search:   
Advanced Search     
  Articles

  ASP (26)
  ASP.NET (19)
  C and C++ (4)
  CFML (2)
  CGI and Perl (16)
  Flash (2)
  Java (7)
  JavaScript (28)
  PHP (92)
  MySQL (13)
  MSSQL (3)
  HTML (34)
  SEO (9)
  Visual Basic (12)
  CSS (13)
  SSI (5)
  XML (12)
  C# (14)

  Developer News

May 15, 2008
Reader Question - Would you host your client's work on your website?
About
 
May 15, 2008
How to Create an Ajax Autocomplete Text Field: Part 6
WebReference.com
 
May 14, 2008
Poll: Are the browser safe colors still needed?
About
 
May 14, 2008
Google Doctype launched
About
 
May 14, 2008
Web Editor Reviews - 6 New Reviews
About
 
May 14, 2008
Build Beautiful Buttons in Photoshop, Part I
SitePoint
 
Courtesy of moreover.com
 
Want to receive new articles via e-mail? Click here!
/Home /JavaScript

Showing and hiding a div 

  Views:    27592
  Votes:    31
by Dan Bailey 12/08/03 Rating: 

Synopsis:

Use the power of the DOM to hide sections of your page and display them when a link is clicked.
Pages: 
The Article

Have you ever wondered how to show different content when different buttons are clicked? In this tutorial you'll find out how.

In the head of your page place the following:

<script type="text/javascript">
function show_div(div_id) {
    // hide all the divs
    document.getElementById('the_div_1').style.display = 'none';
    document.getElementById('the_div_2').style.display = 'none';
    document.getElementById('the_div_3').style.display = 'none';

    // show the requested div
    document.getElementById(div_id).style.display = 'block';
}
</script>

Place this in your page between the <body> and <body> tags:

<a href="" onclick="show_div('the_div_1'); return false;">Div 1</a>
<a href="" onclick="show_div('the_div_2'); return false;">Div 2</a>
<a href="" onclick="show_div('the_div_3'); return false;">Div 3</a>

This will display three links, one for each div. Clicking one of these links will show the relevant div and hide the others.

Then you can place the actual divs anywhere in your page using:

<div id="the_div_1">This is div 1</div>
<div style="display: none;" id="the_div_2">This is div 2</div>
<div style="display: none;" id="the_div_3">This is div 3</div>

You'll notice the second and third divs have a CSS style setting of display:none. This hides them when the page is first loaded, and the first div is displayed. These are displayed accordingly when the links are clicked.

The possibilities for using this are endless. Enjoy!

Pages: 

Similar/related articles:


 
  Sponsors