I want to show-hide the display of these layers with a button click. I can't figure out how to do it with 2 buttons, and 2 divs...
<div id="first">This is the FIRST div</div>
<div id="second">This is the SECOND div</div>
<button id="toggle">Show first div and hide second div</button>
<button id="toggletoo">Show second div and hide first div</button>
#first{
display: none;
}
#second {
display: none;
}
const targetDiv = document.getElementById("first");
const btn = document.getElementById("toggle");
btn.onclick = function () {
if (targetDiv.style.display !== "none") {
targetDiv.style.display = "block";
} else {
targetDiv.style.display = "none";
}
}
https://codepen.io/MaaikeNij/pen/YzrgbQw
I hope you can help me out :)))!!
CodePudding user response:
Try with the following code:
#first{
display: block; /* <--- change */
}
#second {
display: none;
}
const firstDiv = document.getElementById("first");
const secondDiv = document.getElementById("second");
document.getElementById("toggle").onclick = function () {
if (firstDiv.style.display === "none") {
firstDiv.style.display = "block";
secondDiv.style.display = "none";
} else {
firstDiv.style.display = "none";
secondDiv.style.display = "block";
}
}
CodePudding user response:
Correction: you should add eventListener for both toggle & toggletoo. Soulution:
<style>
.hide {
display: none;
}
</style>
<div>
<div>This is the FIRST div</div>
<button >Show first div and hide first div</button>
</div>
<div>
<div>This is the SECOND div</div>
<button >Show second div and hide first div</button>
</div>
<script>
const Toggles = document.querySelectorAll('.toggle');
Toggles.forEach((el) => {
el.addEventListener("click", (e) => {
e.target.parentElement.firstElementChild.classList.toggle('hide');
});
})
</script>
CodePudding user response:
There's lots of ways to do this. One common way I've seen in various templates is to add and remove classes. Another way is to call the function from the button's onclick attribute. But my favorite is to write a function that requires no editing of the div HTML because I don't want to interfere with the HTML guy's work, I just want to put functioning code in there. (BTW, I am positive there is a more elegant way to write this, but here ya go!)
const firstDiv = document.querySelector("#first");
const secondDiv = document.querySelector("#second");
const firstButt = document.querySelector("#toggle");
const secondButt = document.querySelector("#toggletoo");
firstButt.addEventListener("click",toggleDivShowHide);
secondButt.addEventListener("click",toggleDivShowHide);
function toggleDivShowHide() {
if (firstDiv.style.display !== "none") {
firstDiv.style.display = "none";
secondDiv.style.display = "block";
} else {
firstDiv.style.display = "block";
secondDiv.style.display = "none";
}
}
You're saying "if the first div is set to none, then set it to block and set the second div to none. Otherwise, do the opposite."
