Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to hide/reveal a block when clicking on one button?

function questionDisplay() {
  let qBtn = document.querySelector(".question");
  let qTextShow = document.createElement("div");
  qBtn.addEventListener("click", ifElse)

  function ifElse() {
    if(qBtn !== true) {
      qTextShow.className = "info_q";
      qTextShow.innerHTML = `text`
      qBtn.appendChild(qTextShow);
      qTextShow.style.display = "block"
    } else {
      qTextShow.style.display = "none"
    }
  }
}
questionDisplay()

The qBtn button opens a div with text, but does not hide this block when clicking on it, how to fix it?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The most common way is to write your code in your HTML, rather than creating the element with document.createElement(), hiding it by default with CSS utility. class, then use .classList.toggle() to toggle that utility class. Like this:

const some_el = document.getElementById('some_id');

document.getElementById('show_text').addEventListener('click', () => some_el.classList.toggle('hidden'));
.hidden {
  display: none;
}
<div id="some_id" class="hidden">
  Some text
</div>

<button id="show_text">Show text</button>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading