Jump to content

User:Ruud Koot/Javascript

From Wikipedia, the free encyclopedia

Collapsible tables[edit]

// == Collapsible tables ======================================
var autoCollapse = 2;
var collapseCaption = "[hide]";
var expandCaption = "[show]";

function hasClass( element, className ) {
  var Classes = element.className.split( " " );
  for ( var i = 0; i < Classes.length; i++ ) {
    if ( Classes[i] == className ) {
      return ( true );
    }
  }
  return ( false );
}

function collapseTable( tableIndex )
{
    var Button = document.getElementById( "collapseButton" + tableIndex );
    var Table = document.getElementById( "collapsibleTable" + tableIndex );

    if ( !Table || !Button ) {
        return false;
    }

    var Rows = Table.getElementsByTagName( "tr" ); 

    if ( Button.firstChild.data == collapseCaption ) {
        for ( var i = 1; i < Rows.length; i++ ) {
            Rows[i].style.display = "none";
        }
        Button.firstChild.data = expandCaption;
    } else {
        for ( var i = 1; i < Rows.length; i++ ) {
            Rows[i].style.display = "table-row";
        }
        Button.firstChild.data = collapseCaption;
    }
}

function createCollapseButtons()
{
    var tableIndex = 0;
    Tables = document.getElementsByTagName("table");

    for ( var i = 0; i < Tables.length; i++ ) {
        if ( hasClass( Tables[i], "collapsible" ) ) {
            Tables[i].setAttribute( "id", "collapsibleTable" + tableIndex);

            var Button = document.createElement( "a" );
            var ButtonText = document.createTextNode( collapseCaption );
            Button.setAttribute( "id", "collapseButton" + tableIndex );
            Button.setAttribute( "href", "javascript:collapseTable(" + tableIndex + ");" );
            Button.setAttribute( "style", "float: right" );
            Button.appendChild( ButtonText );

            var Header = Tables[i].getElementsByTagName( "tr" )[0].getElementsByTagName( "th" )[0];
            Header.insertBefore( Button, Header.childNodes[0] );

            tableIndex++;
        }
    }

    for ( var i = 0;  i < tableIndex; i++ ) {
        if ( hasClass( Tables[i], "collapsed" ) || ( tableIndex >= autoCollapse && hasClass( Tables[i], "autocollapse" ) ) ) {
            collapseTable(i);
        }
    }
}

addLoadEvent(createCollapseButtons);

// == END Collapsible tables =============================