I generally avoid using "id" and "name" as identifiers because they can cause problems. I'm not sure if they are reserved words or not, but it's best to avoid them.
A definite problem is that you have retrieved a reference to the element that you want to work on and stored it in the variable you are calling
name, but then you are using
div instead of name to try and manipulate it.
Also you're passing the id parameter to the getElementById function inside quotes when you should just use the parameter name without quotes. The
id parameter is a variable that holds a string, but if you put it inside quotes the string "id" will be passed instead of the value that is in the variable.
Lastly, you've correctly used two equal signs to test to see if the style is set to none, but you've also used the double equal sign to try to assign the new value which won't work. Use one equal sign to assign values.
I changed
id to
theId and
name to
el for element and made the other changes and it works for me:
<html>
<head>
<title>Untitled</title>
<script language="JavaScript">
function showAndHide(theId)
{
var el = document.getElementById(theId)
if (el.style.display=="none")
{
el.style.display="block"; //show element
}
else
{
el.style.display="none"; //hide element
}
}
</script>
</head>
<body>
<p><a href="#" onClick = showAndHide('Title')>Some Title</a></p>
<div id='Title' style="display:none">
<a href="http://linkhere/">01-Intro</a>
</div>
</body>
</html>
- <html>
- <head>
- <title>Untitled</title>
- <script language="JavaScript">
- function showAndHide(theId)
- {
- var el = document.getElementById(theId)
- if (el.style.display=="none")
- {
- el.style.display="block"; //show element
- }
- else
- {
- el.style.display="none"; //hide element
- }
- }
- </script>
- </head>
- <body>
- <p><a href="#" onClick = showAndHide('Title')>Some Title</a></p>
- <div id='Title' style="display:none">
- <a href="http://linkhere/">01-Intro</a>
- </div>
- </body>
- </html>
You should also use the
code tag when posting snippets on the forum here, so that they will show up correctly.
When I use this, I seem to jump back up to the top of the page every time I click a link. Is there any way to prevent this?