0

I have a program, where I use JavaScript to make one div appear and another disappear when I click something:

<div id="first" class="active"> some content here </div>
<div id="second" class="inactive"> some content here </div>

<button onclick="change()"> button </button>
function change(){
document.getElementById("first").className="inactive";
document.getElementById("second").className="active"
}
.active{ display: block; }
.inactive{display: none; }

I'd like to make it so that one div fades in while the other fades out.

I've tried transition: ease 1s;, transition: display 1s and using a custom transition, however none of them have worked.

Try clicking the different buttons on this Carrd - the words fade in and out. I'm going for that effect here.

I'd prefer a solution using only HTML, CSS and/or JavaScript -- trying to keep this project simple.

Nimantha
  • 5,793
  • 5
  • 23
  • 56
cm0973
  • 76
  • 2
  • 8

1 Answers1

2

Use opacity:

function change() {
  document.getElementById("first").className = "inactive";
  document.getElementById("second").className = "active"
}
.active{
  opacity:1;
}
.inactive{
  opacity:0;
}
div{
  transition:opacity 1s;
}
<div id="first" class="active"> some content here </div>
<div id="second" class="inactive"> some content here </div>

<button onclick="change()"> button </button>

To prevent the hidden element from taking up space, use:

function change() {
  const f1 = document.getElementById("first");
  f1.style.opacity = "0";
  setTimeout(() => {
    f1.style.display = "none"
    const f2 = document.getElementById("second");
    f2.style.display = "block";
    setTimeout(() => {
      f2.style.opacity = "1";
    }, 50);
  }, 1000);
}
.active {
  display: block;
  opacity: 1;
}

.inactive {
  display: none;
  opacity: 0;
}

div {
  transition: opacity 1s;
}
<div id="first" class="active"> some content here </div>
<div id="second" class="inactive"> some content here </div>

<button onclick="change()"> button </button>
Spectric
  • 27,594
  • 6
  • 14
  • 39