Show/Hide Divs

I need to show/hide certains divs when a link is clicked.

These are my divs:

div1
div2
div3
div4
div5

I will have several links. Depending on which link is clicked it will hide/show several divs simultaneously. For example, if link1 is clicked it will hide div1, div2 and div3 and show div4 and div5.

Thanks,

Sam

Try something like this:

<a href="javascript:void(0);" onclick="showDivs(1); return false;">link 1</a>
<a href="javascript:void(0);" onclick="showDivs(2); return false;">link 2</a>
etc...

<div id="div1" style="display: none;">div 1</div>
<div id="div2" style="display: none;">div 2</div>
etc...

<script>
function showDivs(start)
{
 var div;
 while((div = document.getElementById('div' + start)) !== false)
 {
  div.style.display = (div.style.display == 'none') ? '' : 'none';
  start ++;
 }
}
</script>

That simple function’s first parameter is a starting div number. It will show all divs starting with that one until the last one.

Hi Cyber Alien,

This code looks good. However it doesn’t seem to work properly. Not sure what the problem is, as my understanding of javascript is minimal.

I’ve made a error, it should check if variable div is null, not false. Change while(…) line to this

while(div = document.getElementById('div' + start))

1 <script>
2 function showDivs(start)
3 {
4 var div;
5 while(div = document.getElementById(‘div’ + start))
6 {
7 div.style.display = (div.style.display == ‘none’) ? ‘’ : ‘none’;
8 start ++;
9 }
10 }
11 </script>

Line 4 is giving me an unspecified error.

Let’s start with an HTML page that has links and the divs.


<ul id="items">
    <li><a href="#apple">Apple</a></li>
    <li><a href="#banana">Banana</a></li>
    <li><a href="#grapefruit">Grapefruit</a></li>
    <li><a href="#noisy">Noisy</a></li>
    <li><a href="#watermelon">Watermelon</a></li>
</ul>
<div id="apple">
    <p><a href="http://lifehacker.com/5804509/how-to-split-an-apple-without-a-knife">How to Split an Apple Without a Knife</a></p>
</div>
<div id="banana">
    <p><a href="http://lifehacker.com/5349295/make-quick-ice-cream-with-only-frozen-bananas">Make Quick &#8220;Ice Cream&#8221; with Only Frozen Bananas</a></p>
</div>
<div id="grapefruit">
    <p><a href="http://www.npr.org/2011/04/18/135468567/repelling-bugs-with-the-essence-of-grapefruit">Repelling Bugs With The Essence Of Grapefruit</a></p>
</div>
<div id="noisy">
    <p><a href="http://www.youtube.com/watch?v=eHnnGHgeyC0">Noisy fruit and veggies - Synesthesia</a></p>
</div>
<div id="watermelon">
    <p><a href="http://www.bbc.co.uk/news/world-asia-pacific-13421374">China farmers face 'exploding' watermelon problem</a></p>
</div>

You don’t want the content to be invisible when someone visits with no scripting, so we’ll use scripting to hide the divs as the page is loading.


.hidden {
    display: none;
}

Scripts should be put at the bottom of the page, just before the </body> tag. That’s both for performance reasons, and because it allows us to work directly with page elements before the load event occurs.


...
<body>
    ...
    <script src="script.js"></script>
</body>
</html>

This script is attached to the tabs section, so that we can easily work with the clicked link:


tabs.onclick = function (evt) {
    evt = evt || window.event;
    var link = evt.target || evt.srcElement,
        links,
        i,
        target;
    if (link.nodeType === 1 && link.nodeName === 'A') {
        ...
    }
};

When one of the links is clicked, we want to hide the target div of all of the other links. If the link is for the one that was clicked, we show that one instead. And lastly, we return false to prevent the web browser from doing its default behaviour of loading the link.


links = this.getElementsByTagName('a');
for (i = 0; i < links.length; i += 1) {
    target = document.getElementById(links[i].href.split('#')[1]);

    if (link !== links[i]) {
        target.className = 'hidden';
    } else {
        target.className = '';
    }
}
return false;

Here’s a simple test demo of the technique, which is flexible and can be expanded to meet many different types of needs.

This test code is inline for the sake of posting here, but the css and javascript should normally be placed in a separate external file.


<html>
<head>
<style type="text/css">
#tabs li {
    display: inline;
}
.hidden {
    display: none;
}
</style>
</head>
<body>
<ul id="tabs">
    <li><a href="#apple">Apple</a></li>
    <li><a href="#banana">Banana</a></li>
    <li><a href="#grapefruit">Grapefruit</a></li>
    <li><a href="#noisy">Noisy</a></li>
    <li><a href="#watermelon">Watermelon</a></li>
</ul>
<div id="apple">
    <p><a href="http://lifehacker.com/5804509/how-to-split-an-apple-without-a-knife">How to Split an Apple Without a Knife</a></p>
</div>
<div id="banana">
    <p><a href="http://lifehacker.com/5349295/make-quick-ice-cream-with-only-frozen-bananas">Make Quick &#8220;Ice Cream&#8221; with Only Frozen Bananas</a></p>
</div>
<div id="grapefruit">
    <p><a href="http://www.npr.org/2011/04/18/135468567/repelling-bugs-with-the-essence-of-grapefruit">Repelling Bugs With The Essence Of Grapefruit</a></p>
</div>
<div id="noisy">
    <p><a href="http://www.youtube.com/watch?v=eHnnGHgeyC0">Noisy fruit and veggies - Synesthesia</a></p>
</div>
<div id="watermelon">
    <p><a href="http://www.bbc.co.uk/news/world-asia-pacific-13421374">China farmers face 'exploding' watermelon problem</a></p>
</div>
<script>
var tabs = document.getElementById('tabs');
tabs.onclick = function (evt) {
    evt = evt || window.event;
    var link = evt.target || evt.srcElement,
        links,
        i,
        target;
    if (link.nodeType === 1 && link.nodeName === 'A') {
        links = this.getElementsByTagName('a');
        for (i = 0; i < links.length; i += 1) {
            target = document.getElementById(links[i].href.split('#')[1]);
            if (link !== links[i]) {
                target.className = 'hidden';
            } else {
                target.className = '';
            }
        }
        return false;
    }
};
</script>
</body>
</html>

Hi Paul,

Thanks for sharing this link with me.

It is very useful information to have. Although, I need something very similar but not quite the same as this. Would you be so kind as to advise how to adjust this code.

Your code above shows all of the DIVs until you click one of them and then hides all except for the one you click. What I need is to automatically load one of the DIVs on page load (hiding the rest) and then switch to one of the others when clicked.

So using your code as an example, I would want Apple to be shown on page load and all of the others to be hidden. Then when I clicked on Banana, I would want to hide Apple along with the others and display just Banana. I would also want to style the Active link with a different colour so the user knows which one is already being displayed. So on page load, the Apple link would be red and then when I clicked on Banana, this style would switch to that link.

How would I achieve this?

You would achieve it after setting up the onclick event, by having the script click the first link.


tabs.getElementsByTagName('a')[0].click();

Thanks for your reply Paul.

I’m not as experience with Javascript as some - where in the code do I put that extra line?

At the bottom of the script.

Thanks guys!