Monday, September 28, 2009

Show/hide text on web page



+ What will we discuss today? (Click me.)


You want to make your web page neat and concise but you have too much information to share? You can achieve both by using the drop down text on your web page. Just write down several outlines and when the readers click on any of them, a hidden text block would be dropped down to shown the details.

To implement it, you need to use Javascript. Of course, your readers must enable Javascript in their browsers.

You can do it in simple three steps:

1. Add a Javascript function in your <head> block.
<script type="text/javascript">
function toggleShowHide(elementId) {
    var element = document.getElementById(elementId);
    if (element) {
        if (element.style.display == "none")
            element.style.display = "inline";
        else
            element.style.display = "none";
    }
}
</script>

This function accepts on argument elementId which is the unique id of the HTML element you want to toggle.

When the style.display attribute is set as inline, the HTML element is shown on the web page. When the attribute is set as none, the HTML element is hidden and it doesn't take up any space just like it doesn't exist.

2. Assign an id to the text block you want to hide initially. And hide it.
    <div id="hiddenText" style="display:none">The trick to include a drop down text in your web page.</div>

We assign hiddenText as the id of our hidden text block. We hide it by setting its style.display attribute as none.

3. Define the text the readers can click on to show the hidden text block.
    <p onClick="toggleShowHide('hiddenText')">+ What will we discuss today? (Click me.)</p>

Function toggleShowHide() will be called when this paragraph is clicked. By passing in the element id of hiddenText, which we assigned in step 2, the hidden text block can be dropped down or removed by clicking this paragraph.

No comments:

Post a Comment