Home > Mobile >  Change display Visibility and Boolean Value onclick in JavaScript
Change display Visibility and Boolean Value onclick in JavaScript

Time:07-14

I am trying to change the style display visibility and boolean value(which is a global variable) onclick. Nothing changes with the code I have Written Am I missing anything?

let emojiViewState = false;


const changeView = () => {
    const iconView = document.querySelector(".iconView"); 
    const emojiView = document.querySelector(".emojiView");
        if (emojiViewState===false) {
            emojiView.style.display  = "none";
            iconView.style.display = "block"; 
            emojiViewState = true

        } else if (emojiViewState===true) {
            iconView.style.display = "none";
            emojiView.style.display = "block";
            emojiViewState = false
           
        
    }
};
window.addEventListener("DOMContentLoaded", (event) => {
  const changeViewButton = document.getElementById("changeViewButton");
  changeViewButton.addEventListener("click", (event) => {
            emojiViewState = true
    
        })
}

CSS

   .iconView {
            display: none;
          }
          
          .emojiView {
            display: block;
          }

CodePudding user response:

You should call changeView in the button event listener:

let emojiViewState = false;

const changeView = () => {
  const iconView = document.querySelector(".iconView");
  const emojiView = document.querySelector(".emojiView");
  if (emojiViewState === false) {
    emojiView.style.display = "none";
    iconView.style.display = "block";
    emojiViewState = true;

  } else if (emojiViewState === true) {
    iconView.style.display = "none";
    emojiView.style.display = "block";
    emojiViewState = false;
  }
};

window.addEventListener("DOMContentLoaded", (event) => {
  const changeViewButton = document.getElementById("changeViewButton");
  changeViewButton.addEventListener("click", (event) => {
    changeView();  //  <---  change the view on click
  })
})
.iconView {
  display: none;
}

.emojiView {
  display: block;
}
<div >iconView</div>
<div >emojiView</div>

<button id="changeViewButton">changeView</button>

  • Related