If you're new here, you may want to subscribe to my RSS feed. So that you can read the latest updates about Web2.0 tools, Making Money Online, Tips in SEO, Ajax and many more. Thanks for visiting ProgramimiCOM!
Many times for navigation menus you want to have sub-items of a specific category, but don’t want them to be shown all the time. There is a much easier way to do this than to have something server-side handle this and refresh the page, that way is to use JavaScript. ![]()
Surprisingly, this is easy. The only JavaScript we need is a simple function that takes the id of the element to toggle, than displays or hides it according to the current setting. Doing this involves simply changing the display method to either none or block.
Let’s see some code:
function toggle(id)
{
if(document.getElementById(id).style.display == “none”)
{
document.getElementById(id).style.display = “block”;
}
else
{
document.getElementById(id).style.display = “none”;
}
}
This function takes the specific id of the item we want to toggle, than decides wether to make it visible or hidden using a simple if conditional. Below is a full page using this:
<html>
<head>
<title>Toggle Visibility</title>
<style type=“text/css”>
.subitems
{
margin-left:5px;
}
</style>
<script type=“text/javascript”>
function toggle(id)
{
if(document.getElementById(id).style.display == “none”)
{
document.getElementById(id).style.display = “block”;
}
else
{
document.getElementById(id).style.display = “none”;
}
}
</script>
</head>
<body>
<h2>Categories</h2>
<a href=‘#’ onclick=“toggle(’php’);”>PHP</a>
<ul id=‘php’ style=‘display:none;’ class=’subitems’>
<li>Articles</li>
<li>Tutorials</li>
</ul>
<br /><br />
<a href=‘#’ onclick=“toggle(’css’);”>CSS</a>
<ul id=‘css’ style=‘display:none;’ class=’subitems’>
<li>Articles</li>
<li>Tutorials</li>
</ul>
</body>
</html>
This script implements the toggle function by having two lists, set to display:none at first, toggle their visibility by clicking a link. As you can see, each list has a specific id which is used in the toggle function (php, and css).
Print This Post
Email This Post
Comments RSS
TrackBack Identifier URI
You must be logged in to post a comment.