I want to change the display property of a div tag based on its current display property.
When display = "None", it should switch to "flex" by clicking on it and viseversa.
I wrote the following js code:
window.onload = function showHideSideMenuMyFolders() {
var test = document.getElementById("sideMenuLowerPartFolders_MyFolders");
if (test.style.display === "Flex") {
test.style.display = "None";
}
else {
test.style.display = "Flex";
}
}
It should activate by clicking on a span element in the DOM.
<span id="showSideMenuMyFolders" onclick="showHideSideMenuMyFolders()">
However, it is not working.
Can somebody see my mistake?
3
Answers
Although setting
style.display
can be done in a case insensitive way (like "Flex" or "flex" or "FLEX"), when reading that style property, it will be in all lowercase, so "flex". This means yourif
condition will never be true. You have to compare with the lowercase "flex".The function you are creating is only getting executed once on load.
If you want to use it when the page has ended loading, and on click, declare it before and use it like you’ve done. If you dont need the code to be executed once on load, just dont use the `window.onload’ line.
Also, display properties are in lowercase.
You’re attaching the function to the "window.onload" try just to create a normal function without attach it to "window.onload"
To avoid the use of "window.onload", you can insert the JS on footer, which is recommended.