Forum Moderators: open

Message Too Old, No Replies

Expand / Collapse JavaScript

Need help to add a function.

         

nimonogi

4:07 pm on Aug 22, 2010 (gmt 0)

10+ Year Member



I have the following working JS that will expand/collapse html tables.

What i want is that the tables loads as collapsed instead of expanded, only if browser's JavaScript is enabled.

I'm copying below a separated JS code i found that does this job, and i'm wondering if anyone can help to make it working with the code i'm currently using.


<!-- Expand / Collapse Tables
function Expand(node)
{
// Change the image (if there is an image)
if (node.children.length > 0)
{
if (node.children.item(0).tagName == "IMG")
{
node.children.item(0).src = "minus.gif";
}
}

node.nextSibling.style.display = '';
}

function Collapse(node)
{
// Change the image (if there is an image)
if (node.children.length > 0)
{
if (node.children.item(0).tagName == "IMG")
{
node.children.item(0).src = "plus.gif";
}
}

node.nextSibling.style.display = 'none';
}

function Toggle(node)
{
// Unfold the branch if it isn't visible
if (node.nextSibling.style.display == 'none')
{
Expand(node);
}
// Collapse the branch if it IS visible
else
{
Collapse(node);
}

}

function ExpandAll(num)
{
var node;
var count;
for(var i = 1; i < num; i++)
{
count = "sub" + i;
node = document.getElementById(count);
if (node)
if (node.nextSibling.style.display == 'none') Expand(node);
count = "";
}
}

function CollapseAll(num)
{
var node;
var count;
for(var i = 1; i < num; i++)
{
count = "sub" + i;
node = document.getElementById(count);
if (node)
if (node.nextSibling.style.display != 'none') Collapse(node);
count = "";
}
}
//-->



<!-- Only set closed if JS is enabled
document.getElementsByTagName('html')[0].className = 'isJS';

function tog(dt)
{
var display, dd=dt;
/* get dd */
do{ dd = dd.nextSibling } while(dd.tagName!='DD');
toOpen =!dd.style.display;
dd.style.display = toOpen? 'block':''
dt.getElementsByTagName('span')[0].innerHTML
= toOpen? '-':'+' ;
}
//-->


Thanks a lot!

alias

8:23 am on Aug 23, 2010 (gmt 0)

10+ Year Member



Did you consider of using a JavaScript library like jQuery? That would optimize your current code a lot, and hiding all items on load would be achieved using an example like:

$(function(){
$("div.containter div.item").hide();
});


Of course, the final code would depend on your particular situation.