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; }
Advertisement
Answer
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 class="iconView">iconView</div> <div class="emojiView">emojiView</div> <button id="changeViewButton">changeView</button>