0

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.

3
  • 1
    changeDisplay('id') should be changeDisplay(id). Variables don't have any quotes around them. Same thing for document.getElementById, and divState should be equal to styleState.style.display. Commented Aug 13, 2013 at 20:50
  • @Bucky24 - Ah. Thank you ever so much! Commented Aug 13, 2013 at 20:52
  • 1
    You would be better off using CSS to toggle visibility by adding/modifying the class of the elements. This way the JavaScript doesn't hard code the style. Commented Aug 13, 2013 at 21:01

2 Answers 2

1

(Adding a proper answer rather then leaving it as a comment)

1) changeDisplay('id') should be changeDisplay(id). Variables don't have any quotes around them. Same thing for document.getElementById

2) divState should be equal to styleState.style.display.

Sign up to request clarification or add additional context in comments.

Comments

0

jQuery makes this very simple:

http://api.jquery.com/toggle/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.