Τετάρτη 6 Οκτωβρίου 2010

JavaScript: Expand/Collapse function for any kind of Elements

I have written a simple function in JavaScript that can be used for expansion and collapsion of any kind of element. The expansion/collapsion is performed by changing the value of the style.display between 'none' and ''. Value 'none' means that the element won't be shown at all while '' that the element will be shown.
In order to use this function you should add the attributes groupId having a common value for the elements of the same group (let's say of the same table in the same ul) and collapsable="true" (for those elements of the group that should be able to be collapsed and expanded)

Sample HTML:


<table>
<tr groupid="aTable">
<td>Static row</td>
</tr>
<tr groupid="aTable" collapsable="true">
<td>Show/hide row 1</td>
</tr>
<tr groupid="aTable" collapsable="true">
<td>Show/hide row 2</td>
</tr>
<tr groupid="aTable">
<td>
<a href="onclick()" onclick="expandCollapse('aTable','collapse',this);">expand</a>
</td>
</tr>
</table>


JavaScript function:

function expandCollapse(tableId,collapseMSG,obj){
$("[collapsable='true'][groupId='"+tableId+"']").each(

function(){
if(this.style.display=='none'){
this.style.display='';
}else
this.style.display='none';
}
);
var newMSG=(obj.opp)?obj.opp:collapseMSG;
obj.opp=obj.innerHTML;
obj.innerHTML=newMSG;
}


Notes:

jQuery is prerequired to use this function.

LinkWithin

Blog Widget by LinkWithin

Mobile edition