-1

I want to hide a div (switch) and show another div (hiddenonload) when the button is pressed. I've managed to hide the switch div on press but how do I show the hiddenonload div, when the button is pressed?


My code

var button = document.querySelector("button");
var element = document.querySelector(".switch");

button.addEventListener("click", function() {
    element.classList.toggle("hide");
});
.switch {
    opacity: 1;
}

.switch.hide {
    opacity: 0;
}

.hiddenonload {
    display: none;
}
<div class="switch"> 
  <button>
    <a>Hide me on click</a>
  </button>
</div>

<div class ="hiddenonload">
  <p>Show me</p>
</div>
Community
  • 1
  • 1
Benny
  • 1
  • 1

2 Answers2

1

Just add another classList.toggle to remove the .hiddenonload class of the element you want to show.


Demo

var button = document.querySelector("button");
var element = document.querySelector(".switch");
var element2 = document.querySelector(".hiddenonload");

button.addEventListener("click", function() {
    element.classList.toggle("hide");
    element2.classList.toggle("hiddenonload");
});
.switch {
    opacity: 1;
}

.switch.hide {
    opacity: 0;
}

.hiddenonload {
    display: none;
}
<div class="switch"> 
  <button>
    <a>Hide me on click</a>
  </button>
</div>

<div class ="hiddenonload">
  <p>Show me</p>
</div>

Here's a version with a couple of other improvements :

var toggler = document.querySelector(".toggler");
var button = sw.querySelector("button");
var toshow = document.querySelector(".hidden");

button.addEventListener("click", function() {
    toggler.classList.toggle("hidden");
    toshow.classList.toggle("hidden");
});
.hidden {
    display: none;
}
<div class="toggler"> 
  <button>
    <a>Hide me on click</a>
  </button>
</div>

<div class ="hidden">
  <p>Show me</p>
</div>
Community
  • 1
  • 1
John Slegers
  • 45,213
  • 22
  • 199
  • 169
0

Try this.

var button = document.querySelector("button");
var element = document.querySelector(".hiddenonload");

button.addEventListener("click", function() {
  element.classList.toggle("hiddenonload");
  button.style.display = button.style.display == "none" ? "block" : "none";
});
.switch {
  opacity: 1;
}
.switch.hide {
  opacity: 0;
}
.hiddenonload {
  display: none;
}
<div class="switch">
  <button>
    <a>Hide me on click</a>
  </button>
</div>

<div class="hiddenonload">
  <p>Show me</p>
</div>
Sankar
  • 6,908
  • 2
  • 30
  • 53