JavaScript – Hide or Show an Element

Just about every site I’ve designed has made use of this code block. It utilizes a combination of JavaScript, CSS and some HTML DOM knowledge to get the job done.  Most often I use this to make dynamic menus however the uses are endless.  For this example I will use it for something more simple.

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras dignissim, quam sed pellentesque eleifend, nisi erat facilisis quam, a viverra lorem arcu ut dolor. Morbi in magna mi, vel malesuada diam. Proin pulvinar ultricies aliquam. Sed tellus neque, facilisis eget sagittis eu, cursus in turpis. Phasellus vestibulum turpis nibh. Nam porta congue tellus bibendum sodales. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Duis tellus tortor, aliquet vel mattis vel, sagittis id eros. Ut lacinia lobortis volutpat. Nunc rhoncus sem eu augue mollis dapibus.<br />
<a href="javascript:;" onClick="showLayer('more_content')">Show</a></p>
<p id="more_content">
Fusce sit amet diam odio. Quisque mattis sagittis dui ut malesuada. Curabitur felis velit, varius id scelerisque a, facilisis eu felis. Cras placerat urna ut nulla vulputate quis dignissim arcu tempor. Aliquam laoreet varius sollicitudin. Pellentesque feugiat vehicula risus, ut tristique massa hendrerit ac. Nulla facilisi. Phasellus et nulla erat, sed viverra enim. Curabitur faucibus mi eget quam ultrices non hendrerit tortor consectetur. Etiam iaculis massa et mauris vulputate rhoncus. Proin dapibus mauris in dolor sagittis ut elementum purus mattis.
<br /><a href="javascript:;" onClick="hideLayer('more_content')">Hide</a>
</p>

At this point your page will render both paragraph blocks. In order to hide the second by default we have to add some CSS styling. I could have done this inline for the example however since I consider that to be bad coding practice I will create a style block for that.

p#more_content {
display: none;
}

Now your second paragraph will be hidden by default and the user will have to hit the Show link in order to expand the content. In order to make that functional you will need to add the following JavaScript code.

function hideLayer(whichLayer) {
var menuGroup;
if (document.getElementById) {
// Standard method for modern browsers
menuGroup = document.getElementById(whichLayer).style;

} else if (document.all) {
// For Old IE versions
menuGroup = document.all[whichLayer].style;

} else if (document.layers) {
// For Netscape Navigator 4
menuGroup = document.layers[whichLayer].style;
}
menuGroup.display = "none";
}

function showLayer(whichLayer) {
var menuGroup;
if (document.getElementById) {
// Standard method for modern browsers
menuGroup = document.getElementById(whichLayer).style;
} else if (document.all) {
// For Old IE versions
menuGroup = document.all[whichLayer].style;
} else if (document.layers) {
// For Netscape Navigator 4
menuGroup = document.layers[whichLayer].style;
}
menuGroup.display = "block";
}

This code block could be simplified considerably by using only the getElementById() method, however that will remove it’s backwards compatibility with older browsers. Though the percentage of users visiting with Netscape Navigator 4 or Internet Explorer 4 are extremely low, it could happen, so I have always left those extra lines in just to make sure.

You can also build on this a bit and make it one function that alternates between showing and hiding the div by changing the last line of code to menuGroup.display = menuGroup.display? “”:”block”;.

See it in action


Tags: , , ,

  • Del.icio.us
  • StumbleUpon
  • Reddit
  • Twitter
  • RSS

6 Responses to “JavaScript – Hide or Show an Element”

  1. guest says:

    good job.
    its always better to attach sample example with code ……..

  2. matchu says:

    Orrrrrrr, you could use a Javascript library.

    Any Javascript library.

    Ever.

  3. Gerhard says:

    hey man, you should really check out jquery, you can do what you did here with a fade in and out in 3 lines of code 🙂

  4. marty says:

    Why do you even consider supporting extremely old browsers (Netscape 4, IE4). Avoid using CSS for hide/show behaviour, that’s what JavaScript is for. If old browsers can’t cope with it, users should be upgrading their browsers. We should be educating the users to use modern web standard based browsers and avoid IE4, 5, 5.5 at all costs.

  5. FettesPS says:

    I agree with you that people should be upgrading their browsers, and that we should educate them on doing so. As a web developer I would more than anything to see IE6 die, let alone older versions. Problem is, people still use these browsers. Sure their numbers are dwindling, bu they cant be ignored. As much as I’d love to say “well, it works on my browser, so tough luck” I just can’t get away with that. Believe me, I’ve tried 😉

  6. FettesPS says:

    I actually haven’t tried jQuery, or even looked into it much. Though I do hear it mentioned a lot. Lately I’ve been learning Dojo and my newest project uses that for the vast majority of its JavaScript functionality. However the code required to build my menu looked way more complicated than it needed to be, so I used my old trusty technique and afterwards I thought I’d share it.

Leave a Reply