Show and Hide Elements with JavaScript

One of the benefits of JavaScript is that it can be easily used to manipulate elements on a page without having to refresh or fiddle with complex server-side languages. For example, imagine you have a page of frequently asked questions — you won’t necessarily want all of these to appear at once, so we can hide them with CSS and use JavaScript to show them on demand by manipulating the styling.

The easiest way to hide an element is to set the style attribute to display: none;. The content is still there, but hidden away. Using the example of a FAQ list, we’d construct our question and answer something like this (notice the style on the <span> to hide the question):

<p><a href="#">What price are your apples?</a><br>
<span id="answer1" style="display: none;">Our apples are 30 pence each. If you buy 10 or more we can sell them at a discounted bulk rate of 25 pence each.</span></p>

Next we need to create the JavaScript function that when activated will show our content (in this case, the answer to our question). To do this we use the popular getElementById(), which will allow us to manipulate HTML elements based on their id (note that we gave our first answer an id of ‘answer1′). Once the JavaScript function knows which element we want to play with, we can tell the function to give it a “block” style, which will display our question on the page. The code looks just like this:

<script type="text/javascript">
	function showStuff(id) {
		document.getElementById(id).style.display = 'block';
	}
</script>

Now that we’ve built the function, we can apply it to our page with the onclick event handler so that the JavaScript function knows that when the question is clicked, we apply the showStuff() function:

<p><a href="#" onclick="showStuff('answer1'); return false;">What price are your apples?</a><br>
<span id="answer1" style="display: none;">Our apples are 30 pence each. If you buy 10 or more we can sell them at a discounted bulk rate of 25 pence each.</span></p>

Build the JavaScript, question and answer code into one page and we have a working example:

<html>
<head>
<title>my javascript show script</title>

<script type="text/javascript">
	function showStuff(id) {
		document.getElementById(id).style.display = 'block';
	}
</script>

</head>
<body>

<p><a href="#" onclick="showStuff('answer1'); return false;">What price are your apples?</a><br>
<span id="answer1" style="display: none;">Our apples are 30 pence each. If you buy 10 or more we can sell them at a discounted bulk rate of 25 pence each.</span></p>

</body>
</html>

For each question we want, we’d give the <span> a new id, and show the answer using the showStuff() function (don’t forget to place the id of the answer <span> between the showStuff() brackets, in single quotes: ”).

What if I want to hide the answer again?

Easy enough — we simple reverse the effect of the function with a new function, which resets the styling back to display: none;. The code for this is as follows:

<script type="text/javascript">
	function showStuff(id) {
		document.getElementById(id).style.display = 'block';
	}
	function hideStuff(id) {
		document.getElementById(id).style.display = 'none';
	}
</script>

We would then apply that to an element in the same way as we would showStuff() (don’t forget it’s called hideStuff()!), including the id of the element we wish to hide in the brackets.

Comments

  1. Michael Orozco says:

    You know this is the clearest and most straight forward example i have seen, i have this basic same thing in four different functions in my code, the 5th is not working and i was just tryign to see why…. great job and site,

    GuyWhoCodesWithAchainSaw

  2. I wish you’d show an example of the “showstuff” & “hidestuff” together in the body.
    thanks

  3. Thank you so much. Very easy to understand. Though i just cant understand out to apply the hideStuff.

  4. Great tutorial, just wanted to add this. To show and hide you just need to find out the status of the display.

    if(document.getElementById(id).style.display == ‘block’){
    document.getElementById(id).style.display = ‘none’;
    } else {
    document.getElementById(id).style.display = ‘block’;
    }

  5. I’m trying to remember how to remove the element and the space it would take up if it were there. Could your show an add-on example of removing and maintaning the spacing of the element?
    Some text hidden text ending text.
    In one case: Some text [hidden but space maintained] ending text.
    Other case: Some text ending text.

  6. Wow, this is exactly what I needed. I thinking about using AJAX and imagining the most complicated things to do, and this was extremely easy! Thank you so much. Because of this great article I am going to have a link on my website to this fabulous web resource!

  7. Thanks for this!! :)

  8. Hi there, I think I may finally be getting this, but I’m still tripped up on how to apply the hide stuff function. I can’t have two onClick events, so where do I place the hideStuff code? Thanks!

  9. Thanks a lot- it’s a nice example, which is very easy to understand.
    Is it possible, to combine both (the show and hide) in one link?
    I like to have a link, which is used to open and close/ hide a div-element without having a second link for the hide function.

    Greetings Tobias

  10. Thanks for that short & clear solution!

  11. thanks for the example. really helpful…

  12. Works well. But I have a problem. Imagine that on one page I want to make a link to question #5 on FAQ page. So if I click on link on one page, I would like to be transferred to FAQ page and have question #5 shown (or other hidden). Can you do that? Many thanks for help.

  13. nice and fast

    I updated code so that when clicked again the span will hide again

    function showStuff(id) {
    if(document.getElementById(id).style.display == ‘block’)
    document.getElementById(id).style.display = ‘none’;
    else document.getElementById(id).style.display = ‘block’;
    }

    Very nice as this can be applied to clicking on images as well.

  14. What change would I need to make to hide more than one element? I have it working for 2 elements show and hide but I need it to work for multiple.

    • Copy the code for the question & answer 1 and change “answer1″ to “answer2″, “answer3″ and so forth.

  15. I would like the whole code from start to finnish with the funktion that both shows when klick and hide with klick. And plase dont just put in the letters “id”. Make something up like ex: “shoes” :)
    Best regards

  16. Jem, I’m a moron new to javascript. Could you give me the example of the complete code with answer 2, answer 3 where you only have to click on the question(s) to make the answer(s) appear or disappear?

    that would be VERY nice.

  17. When you just want to hide the answer again, you don’t need to change the value of the “display” attribut from “hide” to “block”. It’s enough to just remove the value.

  18. Carl Armbruster says:

    A few people have suggested checking the element’s display property to see if it is hidden so you can toggle the display. The problem is that the display property is only available to javascript if set with an inline style (which breaks semantic markup). I have a getStyle function below that will get the computed style even if it is set with external CSS.

    Also your example says to show an item with style.display=’block’. This is not the best way to do it. I frequently need to show and hide table cells based on user interaction. A table cell has a display of ‘table-cell’ and setting it block has weird effects, especially in IE. It is always better to show by setting style.display=”” as this will cause it to revert to the default style for the element in all browsers.

    function toggle(el){
    if (typeof(el) == ‘string’) el = document.getElementById(this.id);
    if(el) return;
    if (getStyle(el,’display’)==’none’){
    el.style.display=”;
    } else {
    el.style.display=’none’;
    }
    };

    function getStyle(el,style) {
    if(!el) return;
    /** an element’s style attribute only contains inline styles styles set
    */
    toCamelCase.exp = /-([a-z])/;

    if(!document.getElementById) return;

    var value = el.style[toCamelCase(style)];

    if(!value){
    if(document.defaultView) {
    value = document.defaultView.getComputedStyle(el, “”).getPropertyValue(style);
    } else if(el.currentStyle) {
    value = el.currentStyle[toCamelCase(style)];
    }
    }

    return value;

    /** toCamelCase(input)
    * Converts string input to a camel-cased version of itself.
    * For example:
    * toCamelCase(“z-index”); // returns zIndex
    * toCamelCase(“border-bottom-style”); // returns borderBottomStyle.
    */
    function toCamelCase(s) {
    for(var exp = toCamelCase.exp;
    exp.test(s); s = s.replace(exp, RegExp.$1.toUpperCase()) );
    return s;
    }
    };

  19. Could not find smarter solution than:

    function showhide(id){var e=document.getElementById(id);if( e ) e.style.display = e.style.display ? “” : “none”;}

    [+]
    [-]

    {akoforms=10}

    taken from this site (Russian):
    http://forum.searchengines.ru/showthread.php?t=534183

  20. iloveyou says:

    I just want to say thank-freakin-you for this awesome explanation!! I’m new at javascript and this helps a lot. You rock. ;)

  21. Thanks a lot for this.

  22. Or, you know, $(“#”+id).show(), .hide(), .toggle() … Why reinvent the wheel when JQuery’s done it for you?

    • Because, ‘you know’, this was written in 2007. jQuery was still in its infancy & we didn’t know at the time if it was going to catch on. (There’s also the small but less important factor of sometimes wanting to do something without including a whole library to do it.)

      Of course, you could have offered to write an addendum or indeed an extra post explaining this and instead you had to be a smartarse. Good job!

  23. Not that someone reading this article would be concerned with js performance, but also – http://jsperf.com/jquery-show-hide-vs-css-display-none-block/3

  24. There are times when you want to use an external script to do that especially when your not good or familiar with Jquery, but your right, Jquery has made things simple.

Trackbacks

  1. [...] link. These are some of the things I’m most excited about! I adapted a super cool script from Girls Who Geek (who, incidentally, use the same theme for their blog as me)! When you click on “about” [...]

  2. [...] New Release block and hide it. It's simple enough to do. Here is an example of something similar: Show and Hide Elements with JavaScript – girlswhogeek.com Requires HTML [...]

Add Comment Register



Speak Your Mind

*