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

Time:01-30

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?

CodePudding user response:

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" >
  Some text
</div>

<button id="show_text">Show text</button>

CodePudding user response:

What you have to do in the if is to check if the div you want to appear/disappear is block or not. One way to do this is to use the getComputedStyle() method, which returns the computed values of all CSS properties of an element.

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

  function ifElse() {
    let computedStyle = window.getComputedStyle(qTextShow);
    let display = computedStyle.getPropertyValue("display");

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

CodePudding user response:

function myFunction() {
  var element = document.getElementById("myDIV");
  element.classList.toggle("mystyle");
}
#myDIV {
  display: none
}

#myDIV.mystyle {
  display: block
}
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
  This is a DIV element.
</div>

CodePudding user response:

You can try out this piece of code where hiding and showing an element is done using css classes by the display property of a particular element.

const element = document.querySelector("#element");
const button = document.querySelector(".btn");
button.addEventListener("click",() => {
  element.classList.toggle("hide");
})
.hide{
  display : none;
 }
<div id="element"> This is an element to hide or show </div>
<button > Click Me </button>

  • Related