epgrape
epgrape

Reputation: 41

Javascript onclick() show and onclick() hide

I wanted to make a function with onclick where if I press the div the content should be displayed. If I click on that content it will give me the "starting"-form.

Let me show you the code:

HTML:

<div id="demo">click</div>

Javascript:

var div = document.getElementById("demo");
var info = "This is the information for the user.";     
var status = true;

if(status){
     div.onclick = function() { div.innerHTML = info };
     status=false;
}   
   else {
      div.onclick = function() { div.innerHTML = "click" };
      status=true;
   }

So I made a variable status that checks what is being shown. I hope i could express myself good enough. :)

Upvotes: 0

Views: 371

Answers (1)

epascarello
epascarello

Reputation: 207501

The if statement is not going to magically run again. You need to do the check inside the click. Do not try to bind separate click events.

(function () {
  var div = document.getElementById("demo");
  var info = "This is the information for the user.";
  var status = false;
  div.addEventListener("click", function() {
    status = !status;
    div.innerHTML = status ? info : "click";
  });
}());
<div id="demo">click</div>

Upvotes: 3

Related Questions