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 Commented May 21, 2022 at 19:14

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");
Sign up to request clarification or add additional context in comments.

5 Comments

just use toggle instead of an if/else-statement
@tacoshy good point, that's a neat function I didn't know about. Answer updated
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 they should both work. Note the toggle line replaces the whole JS code I posted, not just the else section.
@JoeHerbert Sorry, I did it differently and I realized I was wrong. Now it works: var element = this.nextElementSibling; element.classList.toggle ("hidden");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.