简体   繁体   中英

Show div hide another div using javascript

My html code looks like this:

<div id="register" class="dropdown">
  <button id="regbutton" href="#" onclick="toggle_visibility('container1');">show1</button>
  <div id="container1" style="display:'none';">
  </div>
</div>
<div id="login" class="dropdown">
  <button id="loginbutton" href="#" onclick="toggle_visibility('container2')"><b>Masuk</b></button>
  <div id="container2" style="display:'none';"></div>
</div>

and this is my js code:

function toggle_visibility(id) {
   var x = document.getElementById(id); {
   if(x.style.display == 'block') {
      x.style.display = 'none';
   } else {
      x.style.display = 'block';
  }
}

The question is, How can I make these divs to be "when one div is visible, the other one is hidden" ?
sorry for my bad English lang :# :3

Firstly add a class to each of the divs here i have it as container then hide all of them, and show the 1 specific div

<div id="register" class="dropdown">
    <button id="regbutton" href="#" onclick="toggle_visibility('container1');">show1</button>
    <div id="container1" class='container' style="display:none;">test
    </div>
</div>
<div id="login" class="dropdown">
    <button id="loginbutton" href="#" onclick="toggle_visibility('container2')"><b>Masuk</b></button>
    <div id="container2" class='container' style="display:none;">test
    </div>
</div>


<script>
    function toggle_visibility(id) {
        var x = document.getElementById(id);
        var divsToHide = document.getElementsByClassName('container'); //divsToHide is an array so we loop through them
        for(var i = 0; i < divsToHide.length; i++){
            divsToHide[i].style.display = "none"; 
        }
        x.style.display = 'block';
    }
</script>

If you only need these two divs, you can simply use their div id's and a simple conditional:

function toggle(divNumber) {
  var div1 = document.getElementById('div1');
  var div2 = document.getElementById('div2');
  if (divNumber == 1) {
    div1.style.display = 'none';
    div2.style.display = 'block';
  } else {
    div2.style.display = 'none';
    div1.style.display = 'block';
  }
}

Fiddle: https://jsfiddle.net/8480twew/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM