Megh Gandhi
Megh Gandhi

Reputation: 103

How to make an on/off switch using javascript?

so when a user clicks on a link a specific element should be shown and when the user clicks that link again the element should hide.I m trying do it but there's a problem with my code.It occurs just once.I want to occur for infinite times.Can anyone help?

<html>

<head>
  <style>
    #test {
      width: 200px;
      height: 200px;
      background-color: black;
      display: none;
    }
  </style>

</head>

<body>
  <script type="text/javascript">
    window.onload = function() {
      var yes = 10;
      for (i = 0; i < 100; i++) {
        if (yes == 10) {
          document.getElementById("test1").onclick = function() {
            document.getElementById("test").style.cssText = "display:block;"
            yes = yes + 1;
            if (yes == 11) {
              document.getElementById("test1").onclick = function() {
                document.getElementById("test").style.cssText = "display:none;"
                yes = yes - 1;

              }

            }
          }

        }

      }


    }
  </script>
  <a id="test1" href="#">link</a>
  <div id="test"></div>
</body>

</html>

Upvotes: 0

Views: 529

Answers (3)

Shomz
Shomz

Reputation: 37701

Not sure why you're doing the loop, but here's how you can do the click part with just one listener:

var el = document.getElementById("test");
document.getElementById("test1").onclick = function() {
  if (el.style.display == "block") {
    el.style.display = "none";
  } else {
    el.style.display = "block";
  }
}
#test {
  width: 200px;
  height: 200px;
  background-color: black;
  display: none;
}
<a id="test1">link</a>
<div id="test"></div>

Upvotes: 1

Tom
Tom

Reputation: 7740

You are doing way more work than you need to do.

Simply check if the div is currently displayed, if it is, hide it, if it isn't show it.

Your script tag can be reduced to:

<script>
  document.getElementById('test1').addEventListener('click', function() {
    var theDiv = document.getElementById('test');

    if(theDiv.style.display === 'block') {
      theDiv.style.display = 'none';
    } else {
      theDiv.style.display = 'block';
    }
  });
</script>

Upvotes: 1

Kos
Kos

Reputation: 72241

You should set onclick only once.

Write the function so that it will first check if the element is visible, and either show it or hide it.

(Also you can use .style.display rather than .style.cssText)

Upvotes: 1

Related Questions