KevMoe KevMoe - 1 month ago 7
HTML Question

Trying to hide all visible divs and show just the selected one

The following code works to toggle visibility on and off, but I want to be able to hide any visible div and show only the one that is visible. Here is the HTML:


<div id="hiddena">
</div>

<div id="hiddenb">
</div>

<div id="hiddenc">
</div>

<div id="hiddend">
</div>

<div id="hiddene">
</div>

</div>

<div id="buttona">
<button type=submit onclick="switchVisible('hiddena');"></button>
</div>

<div id="buttonb">
<button type=submit onclick="switchVisible('hiddenb');"></button>
</div>

<div id="buttonc">
<button type=submit onclick="switchVisible('hiddenc');"></button>
</div>

<div id="buttond">
<button type=submit onclick="switchVisible('hiddend');"></button>
</div>

<div id="buttone" class="tall">
<button type=submit onclick="switchVisible('hiddene');"></button>
</div>


And here is the script...


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

</script>


Does anyone have any suggestions or additions to the script that could accomplish this?

Thanks

Answer

would it be a problem to hide all of them at once and then show up only the one you want?

function hide_them() {
    var divsList = ["hiddena", "hiddenb", "hiddenc", "hiddend", "hiddene"]
    divsList.forEach(function (element) {
        element.style.visibility = "hidden";
    });
}

finally, just call the hide_them function in the begining of your func:

function switchVisible(id) {
   hide_them();
   var e = document.getElementById(id);
   e.style.display = 'block';
}

Another way is to select elements by tag, and hide them all (this is not pretty good way because when your code grows up, it may cause unwanted problems)

Comments