I'm new to javascript, and I'm attempting to use it to toggle the display of several elements. I have written a script to toggle a single element, but my actual site contains several elements over several different pages, so I'd like to write a single function that I can reuse on many different elements.
An example page might be:
<html>
<head>
<title>Some | Page</title>
</head>
<body>
<h1 id="pepper" onclick="changeDisplay('greendiv')">Click Here</h1>
<div id="greendiv" style="height:200px; width:200px"></div>
<script type="text/javascript">
function changeDisplay('id') {
var styleState = document.getElementById('id');
var divState = document.getComputedStyle('id').display;
if (divState == 'none') {
styleState.style.display = 'block';
} else if (divState == 'block') {
styleState.style.display = 'none';
} else {
alert("Error");
}
}
</script>
</body>
</html>
only on the actual site, I put a reference to the external script file containing the code in the <head> tag so I could use the same script on lots of pages. In case it's not obvious from the code, the intent is for me to be able to click the <h1> tag to make the <div> disappear and reappear. I don't know jQuery, although I recently got a book on it, I just haven't had time to start reading, but I'll bet it would make it a whole lot simpler.
I imagine it's something really simple, it's always the really simple stuff that throws me off...
If someone could explain the error in my code, I would really appreciate it.
Whoops, left out the actual problem: The code doesn't do anything. When I click the <h1> element, nothing happens, not even an alert box.
changeDisplay('id')should bechangeDisplay(id). Variables don't have any quotes around them. Same thing fordocument.getElementById, and divState should be equal tostyleState.style.display.