0

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";
    }
  });
}
1
  • classList.add('class-name')? But I guess you want classList.toggle('class-name') so you dont need an if/else-statement
    – tacoshy
    20 hours ago

1 Answer 1

2

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");
5
  • 3
    just use toggle instead of an if/else-statement
    – tacoshy
    20 hours ago
  • @tacoshy good point, that's a neat function I didn't know about. Answer updated 20 hours ago
  • I deleted else and added element.classList.toggle ("hidden"); but it's not working. Instead it works fine as suggested by @JoeHerbert in the first example.
    – Snorlax
    20 hours ago
  • @Snorlax they should both work. Note the toggle line replaces the whole JS code I posted, not just the else section. 20 hours ago
  • @JoeHerbert Sorry, I did it differently and I realized I was wrong. Now it works: var element = this.nextElementSibling; element.classList.toggle ("hidden");
    – Snorlax
    18 hours ago

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.