An HTML website contains mainly text, images, and link controls. A common way of organizing all the controls is by placing the elements into a <div> control. With a <div> control, you can manipulate everything from the font to placement in an HTML page using CSS (cascading style sheets). Note that although the CSS code for manipulation is beyond the scope of this tutorial, we will be using CSS to state whether or not to display a div box.
We begin with an example of a <div> control. At this point, the code does nothing special.
<body>
<div id="myDivBox">
<h2>My Title</h2>
<p>This is some sample text</p>
</div>
</body>
Next, we add CSS that controls whether or not to display the content of the <div> control. The CSS attribute is the keyword ‘display’. The ‘display’ keyword accepts the values ‘block‘, ‘none‘, ‘list-item‘, and ‘inline‘. Our example will utilize ‘none’ that hides the <div> control and ‘block‘ that will display it (as a block as opposed to inline). Our <div> control will intially begin hidden, so let’s add a style attribute to the <div> control as shown below.
<body>
<div id="myDivBox" style="display:none;">
<h2>My Title</h2>
<p>This is some sample text</p>
</div>
</body>
Next, we will add javascript method to control the CSS attributes of our <div> control. As with all javascript, the script belongs in the head. The method is called toggleDiv and accepts no inputs. What the script is doing is checking if the <div> control is in a ‘block‘ or ‘none‘ state. Whichever state is found, we set the opposite.
<head>
<script type="text/javascript">
function toggleDiv()
{
if (document.getElementById("myDivBox").style.display == "block")
{
document.getElementById("myDivBox").style.display = "none";
}
else
{
document.getElementById("myDivBox").style.display = "block";
}
}
</script>
</head>
Finally, we will add an input button that will toggle whether or not to display the <div> control. The input button will call the javascript method via an onClick action.
<body>
<input type="button" value="Toggle" onclick="toggleDiv()">
<div id="myDivBox" style="display:none;">
<h2>My Title</h2>
<p>This is some sample text</p>
</div>
</body>
Here is a working example:
A complete HTML example is listed below. To run this, simply copy the code into a file with an html extension.
<html>
<head>
<script type="text/javascript">
function toggleDiv()
{
if (document.getElementById("myDivBox").style.display == "block")
{
document.getElementById("myDivBox").style.display = "none";
}
else
{
document.getElementById("myDivBox").style.display = "block";
}
}
</script>
</head>
<body>
<input type="button" value="Toggle" onclick="toggleDiv()">
<div id="myDivBox" style="display:none;">
<h2>My Title</h2>
<p>This is some sample text</p>
</div>
</body>
</html>
RSS Feed
Posted in
Tags: 
