I'm using the javascript from this answer but since I want it for multiple pages, sometimes with more or less divs to show/hide I would like to call the function without listing all divId's. I've tried applying the starts with selector and adding a class and calling the class but I can't make it work.
I also made a change to the divVisibility function (replacing the null to divId) because I want to always have one div visible. This works but it seems to me like the first function could be tightened because I have the same line for both if and else operations.
Any help appreciated.
Improving my question. Here's the script with my tiny edit on line 5 of the JS. It currently does work but I want to not have to include all div names ("Div1", "Div2", "Div3", etc) and check if it can be tightened any more.
var divs = ["Div1", "Div2", "Div3", "Div4"];
var visibleDivId = null;
function divVisibility(divId) {
if(visibleDivId === divId) {
visibleDivId = divId;
} else {
visibleDivId = divId;
}
hideNonVisibleDivs();
}
function hideNonVisibleDivs() {
var i, divId, div;
for(i = 0; i < divs.length; i++) {
divId = divs[i];
div = document.getElementById(divId);
if(visibleDivId === divId) {
div.style.display = "block";
} else {
div.style.display = "none";
}
}
}
.buttons a {
font-size: 16px;
}
.buttons a:hover {
cursor:pointer;
font-size: 16px;
}
<div class="main_div">
<div class="buttons">
<a href="#" onclick="divVisibility('Div1');">Div1</a> |
<a href="#" onclick="divVisibility('Div2');">Div2</a> |
<a href="#" onclick="divVisibility('Div3');">Div3</a> |
<a href="#" onclick="divVisibility('Div4');">Div4</a>
</div>
<div class="inner_div">
<div id="Div1">I'm Div One</div>
<div id="Div2" style="display: none;">I'm Div Two</div>
<div id="Div3" style="display: none;">I'm Div Three</div>
<div id="Div4" style="display: none;">I'm Div Four</div>
</div>
</div>