How to make JavaScript work on a second click

Hello, I’m trying to make a button that would toggle an element on and off when clicked but it only works once. How can I fix this?


var box = document.getElementById(“rr”)
function rrr(){
if(box.style.display=“none”){
box.style.display=“block”
} else if (box.style.display=“block”){
box.style.display=“none”
}
}

= is assignment operator
== is how you check for equivalence

1 Like

Nope, still doesn’t work

Hi,

Your creating another else if statement, witch is redundant.
Two points to consider:

  1. Try to don’t use to much global variables.
  2. Since you have a CSS display none: at the beginning, then on your if else statement you need to validate if its block then display none else second click display block.
var box = document.getElementById("rr"); // should be inside the function.
function rrr(){
var box = document.getElementById("rr");
  if (box.style.display === "block") {
        box.style.display = "none";
    } else {
        box.style.display = "block";
    }
}
1 Like

Thanks a lot! I was thinking about this one for weeks!

Your Welcome, Glad to help, just remember if when your DOM loads, will hide the red Box, because you add a CSS style at the beginning to hide the red Box, then you can add your function to first check its block will hide, and it’s hide will do block that way will show and hide on clicking.

Happy Coding :slight_smile:

1 Like