I'm building a sidenav menu. I want to work on the style directly in the css file instead of the Javascript code as below.
For example: dropContent.style.display === "block" and "none", I wish there was a class to modify and not add css values inside the js code. Is this possible ?
References: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_sidenav_dropdown
var dropdown = document.getElementsByClassName("dropdown-btn");
var i;
for (i = 0; i < dropdown.length; i ) {
dropdown[i].addEventListener("click", function() {
this.classList.toggle("activate");
var dropContent = this.nextElementSibling;
if (dropContent.style.display === "block") {
dropContent.style.display = "none";
} else {
dropContent.style.display = "block";
}
});
}
CodePudding user response:
In your CSS:
.hidden {
display: none;
}
In your JS:
if (element.classList.contains("hidden")) {
element.classList.remove("hidden");
} else {
element.classList.add("hidden");
}
Make sure your element has the display property block
to start with and I believe this should give you what you want.
Edit: As @tacoshy points out, there's the toggle function, which is much clearer:
element.classList.toggle("hidden");