Jegsworks: Free Online Computer Lessons Logo:Jegsworks Jan's Illustrated Computer Literacy 101


Home > Resources & Examples > Jan's Web Scripting Demo > Reveal/Hide

Icon: Arrow - Previous pagePrevious    NextIcon: Arrow - Next page


Jan's Web Scripting Demo:
Reveal/Hide

An HTML page does not have to show everything all at once. You can choose to reveal parts only in response to an event, like a click. Many FAQ pages list just the questions at first. You have to click the question to reveal the answer.

Display Property, onClick

Try it: Click on each question to show its answer. (Read them, too!)

Question: What is an FAQ? Arrow down

Question: What's the difference between the display and visibility properties? Arrow down


Visibility Property, onClick

You can use the VISIBILITY property to create a similar effect. How is it different?

Try it: Click on each question to show its answer.

Question: What is an FAQ? Arrow down

Question: What's the difference between the display and visibility properties? Arrow down

Tip: A common coding error is using a value for the wrong property, like using 'hidden' for DISPLAY instead of the correct value, 'none'.


What You Need

To hide and reveal elements, you need:

  1. ID: Each element that needs to be referenced in a script must have an ID.
    This example needed ID for each of the answers and arrows.
    The answers are revealed or hidden.
    The arrows point down when the answer is hidden and up when it is revealed.
  2. Initial style: Hide element initially, either display:none or visibility:hidden
  3. Event attribute that calls a function:
    This example used onClick to call a function specific to that question.

    <span class="question" onClick="showhide0('faqanswer', 'arrow')">

  4. Script that reveals what was hidden:
    This example put the script in the HEAD of the page. It contains four functions and counters, one set for each answer to be revealed. If there were more answers, you would want a more efficient method that used variables. Below is the line of code that shows the first answer.

    document.getElementById(whichanswer).style.display='block';

  5. (Optional) Code in the function that hides what was revealed.
    The example uses If-Else in the script to check a counter. The value of that counter determines if the answer should be revealed or hidden.

    To see the actual code, right click on this page and select View Page Source, or similar command. The script is in the HEAD for the page.

    Refreshing the page would also hide anything that had been revealed.

  6. (Optional) Function that reveals or hides a whole set of elements at once.
    This example does not have such a function. It would usually be attached to a button or a SPAN of text like "Show All".