Expand collapse JavaScript sample

Expand collapse JavaScript sample

If you want to expand and collapse div using JavaScript below is sample code you could use where its using div element and onclick calls JavaScript function to show/hide [+] [-] sign.

Click link to test code: http://jsfiddle.net/javahonk/guSAD/1/

Screen shot:
Expand collapse JavaScript sample

HTML Code:

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<script type="text/javascript">

    function expandCollapse(showHide) {
        
        var hideShowDiv = document.getElementById(showHide);
        var label = document.getElementById("expand");

        if (hideShowDiv.style.display == 'none') {
            label.innerHTML = label.innerHTML.replace("[+]", "[-]");
            hideShowDiv.style.display = 'block';            
        } else {
            label.innerHTML = label.innerHTML.replace("[-]", "[+]");
            hideShowDiv.style.display = 'none';

        }
    }
</script>
<title>Expand collapse sample</title>
</head>
<body>

    <div>
        <table style="width: 500px;" align="center">
            <tr>
                <td onclick="expandCollapse('showHide');" id="expand">[+]
                    Expand/Collapse</td>
            </tr>
        </table>
    </div>

    <div id="showHide" style="display: none;">
        <table style="width: 500px;" align="center">
            <tr>
                <td>Start Date</td>
                <td>End Date</td>
                <td>Amount</td>
            </tr>

            <tr>
                <td>06/05/2013</td>
                <td>06/05/2013</td>
                <td>1000</td>
            </tr>

            <tr>
                <td>06/05/2013</td>
                <td>06/05/2013</td>
                <td>1000</td>
            </tr>

            <tr>
                <td>06/05/2013</td>
                <td>06/05/2013</td>
                <td>1000</td>
            </tr>
        </table>
    </div>
    
</body>
</html>

3 thoughts on “Expand collapse JavaScript sample

  1. This is a very good sample for two layers tree. Could you show me how to display multiple layers for expend/collapse? what do I need to change on java script and html?
    for example I want to be able to display at least three layers of expend/collapse.

    + test1
    + test2
    test…
    test…

Leave a Reply

Your email address will not be published. Required fields are marked *