Simple JavaScript Toggled Divs
I have chosen to go with a very simple code snippit to begin what I hope will be a useful repository of original code snippits. Unless I note otherwise, you are welcome to use any code in my “Code Snippits” post category. I would greatly appreciate it if you let me know you where using the code.Without further delay, this code allows you to easily put areas (of the div type) on your site that can be collapsed and expanded by clicking on a heading. This manipulation is done using JavaScript. In my code below, I have used functions from the MooTools toolkit (a great toolkit to use if you do much JavaScript). So, the installation is pretty straight forward:
1) Download the two icon images and save them in the relative path images/icon_add.png and images/icon_remove.png. You can also use your own icons (they should be 16×16 pixels).
2) Download the MooTools script, and upload it to your server. Then, include it in the HTML document you are working with using:
<script src="mootools-1.2-core-nc.js" type="text/javascript"></script>
You can also get only the parts of MooTools you need (for this script Element and Element.Styles) and compress the package into a small file (helps for faster page loading), by using the utility here.
3) Put the following JavaScript into your HTML page. This can go in the head, but does not have to. However, it should be above the first collapsing box in your code.
<script type="text/javascript">
function toggle(id) {
var el = $(id);
var icon = $(id+'_icon');
if (el.getStyle('display') == 'none') {
el.setStyle('display', 'block');
icon.set({'src':'images/icon_remove.png', 'alt':'[-]'});
} else {
el.setStyle('display', 'none');
icon.set({'src':'images/icon_add.png', 'alt':'[+]'});
}
}
</script>
4) Then, each time you wish to put a collapsing box in, use the following code. I have marked the values you need to change. You must change ‘ID_NAME’ in three places. Within the code for each box, these 3 places should have the exact same value inserted where I have written ‘ID_NAME’. However, if you use more than one box on a page, you cannot use the same value for ID_NAME the next time.
<div onclick="toggle('ID_NAME'); return false;"
style="border: 1px ridge gray; padding: 2px; background: silver;"
alt="[+]" id="ID_NAME_icon" class="icon_inline" align="texttop">
TITLE OF DROPDOWN BOX
</div>
<div id="ID_NAME" style="display: none">
Content of the div goes here.
</div>
About this entry
You’re currently reading “Simple JavaScript Toggled Divs,” an entry on Ryan M. Speers
- Published:
- 07.15.08 / 4pm
- Category:
- Code Snippits

No comments
Jump to comment form | comments rss [?] | trackback uri [?]