Jump to content

Toogle the display property of an element


Goafer

Recommended Posts

OK so this should be pretty easy but for some reason I can't get it working:

The idea is that when the user clicks on a link, it changes the display property of a <div> from 'none' to 'block' and vice versa. 

<script type="text/javascript">
function toggleDisplay()
   {
      if (document.getElementById("test").style.display == "none")
    {
      document.getElementById("test").style.display = "block";
    }
  else
    {
	  document.getElementById("test").style.display = "none";
    }
}
</script>

That's the javascript.

<span onclick="toggleDisplay()">click here</span>

Thats the HTML.

 

The problem is: nothing is happening, at all. In IE it says "error on page" in the bar at the bottom when you click, but other than that, no clues as to why it won't work...

 

Any help appreciated.

 

I've also tried using:

<input type="button" onclick="toggleDisplay()" value="Display" />

- stolen from w3schools.com which didn't work, as well as:

<a href="javascript:toggleDisplay()">Click Here</a>

which I found in some old code, but no luck with those either.

 

I've found it beneficial to unset the display property when "showing". Think of it as "unhiding", especially with table related tags. Firefox supports display properties "table-row" where IE does not. For those cases:

 

style.display = "none"; // to hide

style.display = ""; // to unhide

 

This works with everything.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.