Using javascript to hide and unhide elements dynamically - gHacks Tech News

Using javascript to hide and unhide elements dynamically

My favorite aspect of javascript is that it enables you to add great features to your site like showing/hiding parts of it when a user clicks a link without reloading, get some data from a database and displaying it in a new div, again without reloading. In fact, it would be possible (although not very comfortable and easily codeable) to create a big website, like a WordPress blog without any reloading at all, no matter where you click.

This is usually referred to as AJAX, although most of it is javascript and HTML, and it is actually easier than it seems. In my opinion calling the hiding and showing of elements is not yet AJAX, because in my eyes ture AJAX communicates with the server in the background. We will only be changing CSS properties and element contents with javascript in this post to achieve our goal.

Let's say you're creating a form, and you want a way to explain what the fields do or what data they need to contain, but you don't want to fill up too much space on screen, and you want to make it as unobtrusive as possible. In this case it would be cool to have a link with the anchortext "Explain", which would expand a section which explains what the user needs to do.

As the first step, we need to create a div which will hold the explanation text, and a link which will unhide it for the user.

<a id="link1" href="javascript:display('show', 1)">Explain</a>
<div id="explanation1" style="display:none">This form let's you input your order details, please keep it short!</div>

As you can see I have given the div a unique identifier. This is needed so the javascript knows which div I want to change. I have added a number to the id because there might be many more explanations, these would receive different numbers. I have also given the link an id, with the same number at the end as the div. Once the user clicked the link, we want to change the link, so clicking it again will close the div.

The link contains "javascript:", which indicates that this link doesn't point to a page, but should execute javascript code, in our case a function (display), with two arguments. The first tells the javascript function which will execute that we want to show the div (as opposed to hiding it), the second is a numerical identifier, which should be the same as the number in the div's id. Take a look at the javascript code below with the explanation afterwards.

<script type="text/javascript">

function display(action, id)
if (action == 'show')
document.getElementById("explanation"+id).style.display = "block";
document.getElementById("link"+id).href= "javascript:display('hide', "+id+")";
document.getElementById("link"+id).innerHTML = "Close";

if (action == 'hide')
document.getElementById("explanation"+id).style.display = "none";
document.getElementById("link"+id).href= "javascript:display('show', "+id+")";
document.getElementById("link"+id).innerHTML = "Explain";


As you can see, the two arguments are named "action" and "id". The action argument will tell the script what we want to do (close the div or show it), the id argument will tell it which element we want to do it with. When you first click on the link the action is "show", so let's take a look at what's happening there.

First of all, the script checks what the action is. It sees that it is "show", so it executes three lines. the first line sets the div's dispaly to block, which means that it will appear, you will be able to read the text. this is achieved by "grabbing" the element using its unique id. By specifying "document.getElementById('theidhere')" you can grab any element. In our case, we always grab the element "explanationX", where X is the number beside it, given by the id argument. This id argument makes it possible to use one function for all the divs you want to open or close, so we won't need to code the same function for all the different ids out there. The bit of code following specifies that we want to change the style, more specifically the display property, and we want to change it to "block".

The second line grabs the link element, and instead of changing the style, it changes the address it points to (href), which in our case will be a new piece of javascript code. We change it to the exact same code, but instead of "show" as the action, we now have hide.

Line 3 grabs the same link element, but now changes the element contents. An element's contents is always whatever is between the start and end tag, in a link's case this is the anchor text. We change it from "Explain" to "Close" so the user knows that the div will disappear if he clicks the link again.

The three lines in case the action is "hide" do the exact same things, but change the values back, so if the user wants to open the div again he can do so.

That wasn't so hard was it? The uses for these javascript methods are truly endless, from checking registration forms before submitting, to dynamically adding text to your site, you can do almost anything here, your imagination is truly the limit, so have fun!

We need your help

Advertising revenue is falling fast across the Internet, and independently-run sites like Ghacks are hit hardest by it. The advertising model in its current form is coming to an end, and we have to find other ways to continue operating this site.

We are committed to keeping our content free and independent, which means no paywalls, no sponsored posts, no annoying ad formats or subscription fees.

If you like our content, and would like to help, please consider making a contribution:


  1. Max said on January 15, 2009 at 6:47 am

    More tutorials please! This one is very good.

  2. iampriteshdesai said on January 15, 2009 at 9:00 am

    AJAX, JS, PHP seems to be very useful. Thankfully most websites use them. I use to hate those slow html things to load up. For every stupid click they used to download the entire page again. I learned basic HTML …. thing few days ago, cant wait to learn php.
    PS: Daniel, why don’t you upload images to describe your point?

  3. Stefan said on January 15, 2009 at 9:22 am

    I concur, I’ve just refreshed my basic web design (CSS & HTML) and I’d love to learn some Javascript without just cut/pasting from code snippets.

    Lurn me good, gHacks!

  4. gB said on January 15, 2009 at 11:42 am

    I’m new to javascript so I could very well be missing something. But I’ve copied and pasted (actual Ctrl C and Ctrl V) this code into a basic html file so I could see it action, and clicking on the Explain link does nothing. I’ve tried putting the part both in the head and body and nada. Any clue on a reason why?

  5. gB said on January 15, 2009 at 11:45 am

    Sorry can’t find a way to edit my comment. Just wanted to also add excellent work on the php and now js articles. Keep’em coming.

  6. Paul. said on January 15, 2009 at 1:11 pm

    Hoi Daniel great read again. Is it possible that you make every mounth a .PDF, with that mounth artikels?

  7. Daniel Pataki said on January 15, 2009 at 3:29 pm

    Hi guys!

    Thanks for the praise, I’ll keep ’em coming :)

    Hi gB!
    I should have written about this before, what you need to do is replace ALL the quotes in what you copy pasted with actual quotes. They appear as these weird slanted things in the post, there should always be simple ‘ and ” whenever you see single or duoble quotes.

    I will try and work out something where you can copy-paste!

    Hi Paul!

    Right now I don’t really have time to compile something like that, but if these articles are successful I will think about it :)

    Thanks again for the praise and this is such a great method, I really do love it so, please use it :)

  8. SK Mezanul said on January 15, 2009 at 3:59 pm

    Thanks Daniel, keep these tutorials coming!! they are very useful :)
    and as Paul suggested i too wish for the same, i.e. pdf edition. Thanks. :)

  9. Stefan said on January 15, 2009 at 5:16 pm

    well that was fun – using this technique I managed to put all a (small) site’s content on one page, and use the hiding/unhiding of sections to simulate pagination. Cut down on a hell of a lot of work for me, so thanks again Daniel!

  10. Daniel Pataki said on January 15, 2009 at 5:53 pm

    Happy I could help :) There are loads of other ways to do this, I’ll get to them later. If you put a lot of content in hidden divs it’s actually better to pull the content from another page or db, since then you don’t need to load all of it initally, just the ones visible :)
    More on this later :)

  11. gB said on January 15, 2009 at 6:46 pm

    Wow thanks for the fast response. Fixed the quotes like you said and now it works like a charm.


  12. Daniel Pataki said on January 15, 2009 at 7:17 pm

    No problem gB :) For the same reason you can’t really copy paste link codes and stuff from Word documents unless you do some preparation first :(

    Pretty easy to find & replace, but still a bother.

  13. iampriteshdesai said on January 15, 2009 at 7:21 pm

    I always find this thing to be very annoying on while writing my blog. I type & sign but when I login some time later I find it has changed to &amp, anybody knows why?

  14. eRIZ said on January 15, 2009 at 8:46 pm

    Hey, dude, WT… “javascript”?

    Have you ever heard about unobtrusive event binding?

    var l = document.getElementById('ident'); = function(){ alert('wassup?!'); return false; }

    javascript pseudoprotocol is bad and not semantic…

  15. eRIZ said on January 15, 2009 at 8:47 pm

    err: onclick instead of click; I’ve been working too long with jQuery. ;)

  16. Daniel Pataki said on January 16, 2009 at 1:04 am

    Hi eRIZ!

    I did not know that javascript pseudoprotocol was not the best solution, I’ll switch, thanks :) We live and learn!

  17. Phao Loo said on January 16, 2009 at 2:32 am

    Nice tips, I like thí.
    @eRIZ: instead of using more than 90kb for jQuery for this, just use this code.

  18. Jojo said on January 16, 2009 at 11:53 am

    Maybe you could make a subdomain, say with an index for grouping these lessons?

    1. Martin said on January 16, 2009 at 12:21 pm

      That’s an interesting idea Jojo. I think about it.

  19. jurkis said on January 16, 2009 at 11:55 am

    Let’s say i have a FAQ page.
    How to make this script to open/close Answer by clicking on Question?

    Sorry for my english.

  20. Daniel Pataki said on January 16, 2009 at 8:24 pm

    Hi jurkis!

    Try something like this (use the same js as I have in the post):

    <a id=”link1″ href=”javascript:display(‘show’, 1)”>Question goes here</a>
    <div id=”explanation1″ style=”display:none”>Explanation goes here</div>

    For the secod question you would have:

    <a id=”link2″ href=”javascript:display(‘show’, 2)”>Question goes here</a>
    <div id=”explanation2″ style=”display:none”>Explanation goes here</div>

  21. eRIZ said on January 16, 2009 at 10:57 pm

    ~Phao Loo: 90 KiB? Huh, uncompressed version…

    But compressed not as big as the biggest one.

    What’s a problem selecting a part of code which manages event binding? jQ is modular. ;)

  22. Damon said on March 11, 2010 at 12:26 am

    Awesome! I’m just learning HTML and CSS now, and will get into JS soon enough, but this will be a big help on what I wanted to do. (:

  23. Mark said on May 8, 2010 at 11:50 am

    Fantastic. Exactly what I needed.

  24. tyra_0729 said on June 27, 2010 at 1:37 pm

    thx! i found what i want here

  25. Faze said on July 12, 2010 at 1:15 pm

    Excellent! Very very useful! Thank you!

  26. Faze said on July 12, 2010 at 1:30 pm

    Following on from the FAQ example, how would you change the JS so that you could make the page display the riginal text for the link when you close it, rather than “Explain” (or any other standard text)…as each question would presumably have a different text displayed…?


  27. icesurfer said on November 3, 2010 at 8:13 pm

    This would be a good tutorial, but you left half of it out. It’s obvious to me that your neglect in putting in html code examples makes it all but useless to the novice. Being fairly experienced I figured out how to do it on my own, but I expect most people will not be able to do that so easily.

    If you’re going to take the time to do something, take the time to do it right. Otherwise, don’t bother!

    Please let me know when you correct this very substandard article!

  28. psmail said on November 5, 2010 at 4:47 am

    This was super useful – thanks

  29. Uma said on November 12, 2010 at 11:07 am

    Really good one! Thanks a lot…

  30. Rolando said on February 5, 2011 at 12:44 am

    Very Nice. Thanks a lot friend.

  31. Joe said on March 6, 2012 at 8:53 am


    Thanks for this script. I’m trying to twist things around a little- how would the script read to have multiple DIVS hide and show with one click?

  32. Anonymous said on June 29, 2012 at 11:47 pm

    wow! this is an awesome example

  33. Lukasz said on October 12, 2012 at 8:54 pm

    It’s perfect!
    Huge thanks man, I was looking for this for ages.

  34. Habib said on April 2, 2013 at 3:24 am


Leave a Reply

Check the box to consent to your data being stored in line with the guidelines set out in our privacy policy

Please note that your comment may not appear immediately after you post it.