It's Sean!

UK freelance journalist, author
and copywriter Sean McManus

Printed from www.sean.co.uk. © Sean McManus.
Home > Articles > Webmaster resources > Javascript examples > Javascript hide / reveal script

Using Javascript to hide and reveal text and graphics

One of the most useful things you can do with javascript and CSS is to make things appear and disappear when you want to. It means you can focus the user's attention on what's needed at a particular stage of a process (eg e-commerce), or you can create special effects by making text or graphics pop onto the screen instantly.

I created a tool that enables people to get their copy of my novel University of Death signed over the internet. This uses the script to good effect to make the 'signed' letter instantly appear.

There are lots of javascript and CSS libraries that have features built in to hide and reveal different sections of the page, but they usually carry a heavy download penalty. Unless you wanted to use the library for something else (and something much more difficult, at that), then you're better off adapting this short free script to hide and reveal webpage content.

Shall we try an example?

I've got hiccups. Give me a surprise!

How it works

This is easy. Here are three steps to getting it working:

  1. Create the content you want to hide. Put it inside a DIV and give it an ID. Let's call our DIV 'hideaway'. If you have more than one on a page, give them different names. You also need to set the style to "display:none;" if you want it to start off hidden. It should look like this:
    <div id="hideaway" style="display:none;">Here's the hidden content</div>
  2. Create your link and put in the following Javascript:
    <a href="javascript:;" onClick="document.getElementById('hideaway').style.display='block';">Reveal hidden content</a>
  3. To create a link that hides it again, using the following Javascript:
    <a href="javascript:;" onClick="document.getElementById('hideaway').style.display='none';">Hide content again</a>

The content that you make appear and disappear can include image tags and any other HTML - it's just text in the above to make it easier to understand.

More advanced stuff you can do

That technique is fairly basic, but it underlines some quite sophisticated effects. Here are some ideas for other ways to use it: