Show And Hide With Javascript

show and hide screenshot

show and hide screenshot

I’m sure you’ve seen this simple feature a lot while surfing the net. You know the one; a list of headings that, when clicked, reveal some more content. A good example is a FAQ page.

Let’s start this snippet with the barebones html:

HTML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Show And Hide :: Javascript</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<ul id="mylist">
    <li>
        <h2>Heading 1<a title="open this section">close this section</a></h2>
        <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque ac lectus. In vitae tortor id quam accumsan hendrerit.</p>
    </li>
    <li>
        <h2>Heading 2<a title="open this section">open this section</a></h2>
        <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque ac lectus. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. </p>
    </li>
    <li>
        <h2>Heading 3<a title="open this section">open this section</a></h2>
        <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque ac lectus. In vitae tortor id quam accumsan hendrerit. Fusce semper consectetuer eros.</p>
    </li>
</ul>
</body>
</html>

As you can see, this is very straightforward html. We have an unordered list. Inside each list item, we have a heading with an anchor nested inside and after the heading, a paragraph.

An important point to note is that the anchor text is different for the first list item as this will be visible when the page loads.

Now, let’s style that html with CSS:

CSS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
* {
    margin:0;
    padding:0;
}
ul {
    list-style:none;
    width:50%;
}
ul li {
    border:1px solid #ccc;
}
ul li h2 {
    background-color:#eee;
    color:#435;
    padding:5px 10px;
    font-family: Georgia, sans serif;
}
h2 a {
    font-size:0.6em;
    padding-left:30px;
    cursor:pointer;
    display:none;
}
ul li p {
    background-color:#f9f9f9;
    color:#567;
    padding:5px 10px;
}

Most of the CSS here is to give our example some basic presentation but there are 2 important points that you should take note of. Both points concern the anchor. Because the anchor isn’t a ‘link’ i.e. it doesn’t have an ‘href’ attribute, when you hover the mouse over it, the mouse cursor won’t change to the usual ‘pointer’ that you expect from a link. Therefore we specify ‘cursor:pointer’ in the CSS. Secondly, we set the display rule for the anchor to ‘none’. This is so that users viewing the site without javascript won’t be presented with a ‘link’ that doesn’t work. Instead, we’ll make the anchor appear only for users with javascript enabled.

Now let’s see the javascript

Javascript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<script type="text/javascript">
window.onload = function () {
    var mylist = document.getElementById('mylist');
    var clickers = mylist.getElementsByTagName('a');
    var paras = mylist.getElementsByTagName('p');
    for (var i = 1;i < paras.length;i++) {
        paras[i].style.display = "none";
    }
    for (var i = 0;i <clickers.length;i++) {
        clickers[i].style.display = "inline";
        clickers[i].onclick = function () {
            if (this.parentNode.nextSibling.style.display == "none") {
                this.parentNode.nextSibling.style.display = "block";
                this.firstChild.nodeValue = "close this section";
            } else {
                this.parentNode.nextSibling.style.display = "none";
                this.firstChild.nodeValue = "open this section";
            }
        }
    }
}
</script>

That might look a bit scary but it’s not too bad if we break the code down in to manageable chunks. First, we initialise our variables. We identify the list, the anchors and the paragraphs.

3
4
5
var mylist = document.getElementById('mylist');
var clickers = mylist.getElementsByTagName('a');
var paras = mylist.getElementsByTagName('p');

Then we loop through the paragraphs and hide them. Note that we start counting from index[1]. This is the second paragraph in the list (in javascript, indexing starts at 0). This is because we want the first paragraph to be visible when the page loads.

6
7
8
for (var i = 1;i < paras.length;i++) {
    paras[i].style.display = "none";
}

Next, we loop through the anchors and set each to display on the page.

9
10
for (var i = 0;i <clickers.length;i++) {
    clickers[i].style.display = "inline";

Still within the loop, we assign an onclick event to each anchor

11
clickers[i].onclick = function () {

The next part uses the DOM to target the relevant paragraph. If the paragraph is visible, we hide it and vice versa. We also change the text inside the anchor before closing our function.

12
13
14
15
16
17
18
19
20
if (this.parentNode.nextSibling.style.display == "none") {
    this.parentNode.nextSibling.style.display = "block";
    this.firstChild.nodeValue = "close this section";
    } else {
    this.parentNode.nextSibling.style.display = "none";
    this.firstChild.nodeValue = "open this section";
    }
}
}

Finally, the entire code is wrapped inside the window.onload event

window.onload = function () {
}

Now you have a working show and hide effect that degrades nicely for users without javascript. You can see an example here.

Feed IconFollow me on Twitter





Make ElanMan happy and be the first to comment.

Leave a Comment







XHTML: You can use the following tags in your comments: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">