简体   繁体   中英

JS Toggle Visibility: How to Hide Already Visible Elements on Click

I'm using Javascript to show / hide elements on a page when I click the links. It works as expected. However, when I click on the links, I want all other visible elements to be hidden. How can I achieve this? Thank you in advance!

Here's my code:

**JS**

<script type="text/javascript" async>
<!--
function toggle_visibility(id) {
   var e = document.getElementById(id);
   if(e.style.display == 'block')
      e.style.display = 'none';
   else
      e.style.display = 'block';
}
//-->
</script>


**CSS/HTML**

div {
display:none;
}

<a href="#" onclick="toggle_visibility('punctuation');">PUNCTUATION</a>
<a href="#" onclick="toggle_visibility('grammar');">GRAMMAR</a>

<div id="punctuation">
Punctuation stuff
</div>

<div id="grammar">
Grammar stuff
</div>

First set all elements to the display of the item u are toggling. and then set the element you are toggling to the opposite.

function toggle_visibility(id) {

   var e = document.getElementById(id);
   var curDisplay = e.style.display;
   el = document.getElementsByClassName('foo');
   el.forEach(function(e){
       // this can be set as 'none' is you want hide instead of toggle
       e.style.display = curDisplay;
   }) 

   if (curDisplay == 'block')
       e.style.display = 'none';
   else
       e.style.display = 'block';
}


<div class="foo" id="punctuation">
Punctuation stuff
</div>

<div class="foo"  id="grammar">
Grammar stuff
</div>

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