Using javascript to hide and unhide elements dynamically

Daniel Pataki
Jan 15, 2009
Updated • Dec 15, 2012
Development
|
37

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";
}
}

</script>

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!

Advertisement

Previous Post: «
Next Post: «

Comments

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

    Thanks

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

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

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

    wow! this is an awesome example

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

    Hi!

    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?

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

    Very Nice. Thanks a lot friend.

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

    Really good one! Thanks a lot…

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

    This was super useful – thanks

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

    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!

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

    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…?

    Thanks

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

    Excellent! Very very useful! Thank you!

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

    thx! i found what i want here

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

    Fantastic. Exactly what I needed.

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

    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. (:

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

    ~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. ;)

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

    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>

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

    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.

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

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

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

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

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

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

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

    Hi eRIZ!

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

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

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

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

    Hey, dude, WT… “javascript”?

    Have you ever heard about unobtrusive event binding?

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

    javascript pseudoprotocol is bad and not semantic…

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

    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?

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

    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.

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

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

    Awesome

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

    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 :)

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

    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!

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

    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. :)

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

    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 :)

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

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

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

    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.

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

    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?

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

    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!

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

    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?

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

    More tutorials please! This one is very good.

Leave a Reply

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

We love comments and welcome thoughtful and civilized discussion. Rudeness and personal attacks will not be tolerated. Please stay on-topic.
Please note that your comment may not appear immediately after you post it.