0

I am trying to hide and display a div based on the state of a checkbox using javascript but I don't seem to be getting it right. I am not very experienced with js so I could be missing something very obvious. Any advice would be much appreciated. the target div is the on-toggle div in the second half of the html code.

var checkbox = document.querySelector("input[name=toggle]");

checkbox.addEventListener( 'change', function() {
    if(this.checked) {
        document.getElementById("on-toggle").style.display = "block";
        document.getElementById("on-toggle").style.height = "auto";
    } else {
        document.getElementById("on-toggle").style.display = "none";
        document.getElementById("on-toggle").style.height = "0";
    }
<div id="switch">
                <h2 id="CTA-switch">Turn creativity on </h2>
                <div class="switch">
                	<input type="checkbox" name="toggle">
                	<label for="toggle">
                    <i class="bulb">
                      <span class="bulb-center"></span>
                      <span class="filament-1"></span>
                      <span class="filament-2"></span>
                      <span class="reflections">
                        <span></span>
                      </span>
                      <span class="sparks">
                        <i class="spark1"></i>
                        <i class="spark2"></i>
                        <i class="spark3"></i>
                        <i class="spark4"></i>
                      </span>
                    </i>    
                  </label>
                </div>
            </div>

<div id="on-toggle"> 
    <div id="references">
        
        <h1>REFERENCE SITES</h1>
        

            </div>
        </div>
    </div>

2
  • 4
    Which element are you trying to toggle? Your script indicates it will have id on-toggle, but your html has no element of this, or indeed any similar, id. Commented Apr 20, 2020 at 18:54
  • Yes sorry, the element does exist in my code. It contains a grid of buttons and images. I forgot to add the snippet in Commented Apr 21, 2020 at 7:42

1 Answer 1

1

You'll need to grab an actual element so your javascript code works. The id "on-toggle" does not currently exist on any element on your html code.

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

1 Comment

Hi there, sorry I forgot to add that snippet in. The ID does exist and contains a grid of buttons and images.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.