Reputation: 92
So basically I have a jQuery function attached to some folder icons that toggle the visibility of different divs:
$(document).ready(function() {
$("#techfolder").click(function(){
$("#txt").toggleClass("d-none");
});
$("#persfolder").click(function(){
$("#txt2").toggleClass("d-none");
});
$("#linkfolder").click(function(){
$("#txt3").toggleClass("d-none");
});
});
The only problem is that if one element is visible and you don't click its folder to make it disappear before clicking another folder associated with a different element, the newly visible element appears below the first one. I want to make it so that visibility is exclusive for these elements, and only one can be showing at a time. I can't seem to figure out how to make that happen.
Any help is greatly appreciated!
Upvotes: 0
Views: 288
Reputation: 423
this might not be the simplest way but what you could do is mention all unique elements within an array, then fire a check to see if the element inside the element you've clicked on is a child, then toggle the display none.
If it isn't a direct child, then fire a check to see if 'd-none' is active or not, then toggle it.
There's probably a far simpler way but this answer is based on the assumption you're keeping the HTML as you are.
var arrayOfElements = [$("#txt"), $("#txt2"), $("#txt3")];
$('#techfolder, #persfolder, #linkfolder').click(function(){
checkDisplayNone($(this));
});
function checkDisplayNone(elem) {
innerElem = elem.children();
for (i = 0; i < arrayOfElements.length; i++) {
if (innerElem[0].id !== arrayOfElements[i][0].id) {
if (!arrayOfElements[i].hasClass('d-none'))
arrayOfElements[i].toggleClass('d-none');
} else {
arrayOfElements[i].toggleClass('d-none');
}
}
}
#techfolder {
width: 100px;
height: 100px;
background: red;
margin: 1rem;
}
#persfolder {
width: 100px;
height: 100px;
background: blue;
margin: 1rem;
}
#linkfolder {
width: 100px;
height: 100px;
background: green;
margin: 1rem;
}
.d-none {
display: none;
}
<html>
<div id="techfolder">
<div id="txt" class="d-none">
text
</div>
</div>
<div id="persfolder">
<div id="txt2">
text
</div>
</div>
<div id="linkfolder">
<div id="txt3">
text
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</html>
Upvotes: 1