Monday, November 7, 2011

How to hide and show div block with Javascript

1. Javascript
Add to the header the script that will hide/show div you need

<script language="JavaScript">
    function toggle(id) {
        var state = document.getElementById(id).style.display;
            if (state == 'block') {
                document.getElementById(id).style.display = 'none';
            } else {
                document.getElementById(id).style.display = 'block';
            }
        }
</script>

2. CSS
In order to hide your div at the beginning add this to your CSS style:

#div1 {
        display:none;
}

HTML
In your HTML add hyperlink that will trigger the script for the id with the specific name:

<a href="#" onclick="toggle('div1');">Your text is here</a>

<div id="div1">
The content of this div will be hidden or shown after click on the link above.
</div>

No comments: