Over the last few years the naughty JavaScript child has grown up a bit. The The prototype project has swept away a the cross browser unpleasantness, extended the DOM and made the entire thing a lot more like a proper grown up coding language. So in the spirit of playing with an adult I whipped up a collapsible link control using the prototype library.
I’ve published a demo of the collapsible links and the images are a plus and a minus and can be grabbed from the above link. The code uses divs to construct the tree
The code uses divs to construct the tree. Css is used to show and hide the div panels and swap the plus and minus images. Prototype enabled JavaScript is used to wire it together
<html>
<head>
<script src="scripts/prototype.js"></script>
<script>
function setupGrid()
{
arrLinks = $$('#JsGrid a');
for(var i=0;i<arrLinks.length;i++)
{
arrLinks[i].observe('click', togglePanel);
}
}
function togglePanel()
{
var clickedLink = Event.element(event);
var panel = clickedLink.up().next();
if(clickedLink.className == "linkOpen")
{
clickedLink.className = "linkClose"
}
else
{
clickedLink.className = "linkOpen"
}
if(panel.className == "panelClose")
{
panel.className = "panelOpen"
}
else
{
panel.className = "panelClose"
}
}
</script>
<style type="text/css" >
.panelOpen
{
padding: 0px 0px 0px 20px;
display:block;
}
.panelClose
{
padding: 0px 0px 0px 20px;
display:none;
}
.linkOpen
{
padding: 0px 0px 0px 20px;
background:url('images/minus.gif') no-repeat center left;
}
.linkClose
{
padding: 0px 0px 0px 20px;
background:url('images/plus.gif') no-repeat center left;
}
</style>
</head>
<body onload="setupGrid();">
<div id="JsGrid">
<div><a href="#" class="linkOpen">Test 1</a></div>
<div class="panelOpen" >Test content 1</div>
<div><a href="#" class="linkOpen">Test 2</a></div>
<div class="panelOpen">Test content 2</div>
<div><a href="#" class="linkOpen">Test 3</a></div>
<div class="panelOpen">Test content 3</div>
<div><a href="#" class="linkOpen">Test 4</a></div>
<div class="panelOpen">Test content 4</div>
</div>
</body>
</html>
The setupGrid method wires the togglePanel method to the click event of each link. The
$$('#JsGrid a');
is prototype cleverness to pick up all the links under the JsGrid element. The togglePanel
function does what it says on the tin – shows and hides the panel giving the collapsible tree structure its collapsibility. The only prototype sprinkle is clickedLink.up().next();
which shows off the prototype DOM navigation rather than the old document.getElementById
unpleasantness.All in all I was surprised how little code it took and how readable the code was. Mmmm, tasty and virtually calorie free.