You've seen expand/collapse blocks just about everywhere on the Internet! Ever wanted to know how to make your own? You'll be surprised at how simple it is - just a few lines of JavaScript will let you toggle any block of content on your webpage.
Let us start with a simple block of text (it could as well contain images and any other content) that we wish to make toggle-able:
<div id="content">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nunc fermentum.
</div>
Next, we add a link that toggles the block when clicked:
<a href="#" onclick="toggle('content')">Toggle</a>
All that is left is the actual toggle function. The toggle function itself is quite simple: it takes the ID of the element to toggle and uses the CSS display property to show/hide it. By default, the display property is blank. (unless specified otherwise in the CSS) To hide an element, you just set display to 'none'. The code goes like this:
<script type="text/javascript">
function toggle(id) {
var e = document.getElementById(id);
if (e.style.display == '')
e.style.display = 'none';
else
e.style.display = '';
}
</script>
Put the above 3 code fragments together and you've got a working expand/collapse block.
In the above example, the block is initially visible. To have the block hidden by default, simply modify the first line as follows:
<div id="content" style="display:none">
Reference:
http://www.ozzu.com/javascript-tutorials/tutorial-expand-collapse-blocks-and-navigation-trees-t89202.html
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.