Suraj Roy Suraj Roy - 5 months ago 12
jQuery Question

Toggle visibility of all divs at once

i have multiple divs with id = e. also multiple divs with id = b. now i want to hide all divs with id e and show all divs with id b. this should be done using toggle. so that again clicking on button shows all divs with id e and hides all divs with id b.

<script>
function toggle_visibility(e, b) {
var e = document.getElementById(e);
var e2 = document.getElementById(b);
if(e.style.display == 'none') {
e.style.display = 'inline-block'; //block will show the conain in div
e2.style.display = 'none';
}
else {
e.style.display = 'none';
e2.style.display = 'inline-block';
}
}
</script>
<style>
.menu{
display:inline-block;
border:1px;
border-style: solid;
border-color: black;
width:auto;
height:30px;
padding: 5px;
margin: 2px;
}
</style>
<a href="#id" onclick="toggle_visibility('e', 'b');">Change</a>

<div id="e" class="menu">Male</div><div id="b" class="menu" style="display: none;">পুরুষ</div>

<div id="e" class="menu">Female</div><div id="b" class="menu" style="display: none;">মহিলা</div>

Answer

id has to be unique...You can target multiple elements using having common class name like so:

     function toggle_visibility(e, b) {
       var e = $(".e");
       var e2 = $(".b");
       if (e.is(":visible")) {
         e2.show();
         e.hide();
       } else {
         e2.hide();
         e.show();
       }
     }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#id" onclick="toggle_visibility('e', 'b');">Change</a>

<div id="e" class="menu e">Male</div>
<div id="b" class="menu b" style="display: none;">পুরুষ</div>

<div id="e" class="menu e">Female</div>
<div id="b" class="menu b" style="display: none;">মহিলা</div>

Comments