Home > Back-end >  Create a loop for the script code below the menu
Create a loop for the script code below the menu

Time:12-25

I used the following code on my site:

let txt_com = document.querySelector(".text_user");
let num_com_user = document.querySelector(".massage_for_user");

txt_com.addEventListener("click", function() {
  if (this.classList.contains("num_com_user")) {
    this.classList = "num_com_user";
    num_com_user.style.display = "none";
  } else {
    this.classList = "num_com_user";
    num_com_user.style.display = "block";
  }

  return;
})
<div >
  <div >
    <span >click</span>
  </div>

  <span >No text found!</span>
</div>

But this code is executed only once and I have to refresh the page next time. I just want the menu to open or close every time I click on the post.

CodePudding user response:

First, there's no need for a loop. Don't try to do CSS's job in JavaScript. There's no need to edit the .style property when you can just toggle a class instead.

It's better to practice to write a utility class, such as .hidden that hides an element, then toggle that class on the element you need to hide/show. Like this:

let txt_com = document.querySelector(".text_user");
let num_com_user = document.querySelector(".massage_for_user");

txt_com.addEventListener("click", function() {
  num_com_user.classList.toggle('hidden');
  
  // any code put here will run every time the menu is clicked
})
.hidden {
  display: none;
}
<div >
  <div >
    <span >click</span>
  </div>

  <span >No text found!</span>
</div>

  • Related