Having added multiple div elements with different IDs, I am facing an issue where clicking one div displays it while hiding the others. I am looking for a solution to prevent conflicts between the divs. Any suggestions on what might be causing this problem?
var divs = ["on1", "off1", "on2", "off2", "on3", "off3"];
var visibleDivId = null;
function divVisibility(divId) {
if (visibleDivId === divId) {
visibleDivId = null;
} 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;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="main_div">
<div class="buttons">
<a href="#" onclick="divVisibility('on1');">On</a> |
<a href="#" onclick="divVisibility('off1');">Off</a> |
</div>
<div class="inner_div">
<div id="on1">I'm Div One</div>
<div id="off1" style="display: none;">I'm Div Two</div>
</div>
</div>
<div class="main_div">
<div class="buttons">
<a href="#" onclick="divVisibility('on2');">On</a> |
<a href="#" onclick="divVisibility('off2');">Off</a> |
</div>
<div class="inner_div">
<div id="on2">I'm Div One</div>
<div id="off2" style="display: none;">I'm Div Two</div>
</div>
</div>
<div class="main_div">
<div class="buttons">
<a href="#" onclick="divVisibility('on3');">On</a> |
<a href="#" onclick="divVisibility('off3');">Off</a> |
</div>
<div class="inner_div">
<div id="on3">I'm Div One</div>
<div id="off3" style="display: none;">I'm Div Two</div>
</div>
</div>