John
John

Reputation: 443

css keyframe animation reverse

I am trying to have a large hidden at the top of the page and when the user clicks the button it slides down and if the user clicks the button again it slides back up, etc. I'm not really sure why this isn't working, any ideas?

document.getElementById("button").addEventListener("click", function() {
  var x = document.getElementById("one");
  if (x.style.animation === "shrink .8s") {
    x.style.animation = "shrink .8s";
  } else {
    x.style.animation = "expand .8s";
  }
});
#one {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  background-color: black;
  animation: shrink .8s;
  animation-fill-mode: forwards;
  
  z-index: -1;
}

@keyframes expand {
  100% {
    top: 0;
  }
}

@keyframes shrink {
  100% {
    top: -100vh
  }
}
<button id="button">Click</button>

<div id="one"></div>

Upvotes: 2

Views: 798

Answers (1)

Temani Afif
Temani Afif

Reputation: 272842

The issue is that when you change the animation it will be considred from the initial state of your element and not the final state of the previous animation. So you won't have the intended result using animation (even if we correct your JS code as it's not the correct way to test your animation)

document.getElementById("button").addEventListener("click", function() {
  var x = document.getElementById("one");
  x.classList.toggle('expand');
});
#one {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  background-color: black;
  animation: shrink .8s;
  animation-fill-mode: forwards;
  z-index: -1;
}

#one.expand {
  animation: expand .8s;
}

@keyframes expand {
  100% {
    top: 0;
  }
}

@keyframes shrink {
  100% {
    top: -100vh
  }
}
<button id="button">Click</button>

<div id="one"></div>

In such case better use transition by toggling a single class to change the top property:

document.getElementById("button").addEventListener("click", function() {
  var x = document.getElementById("one");
  x.classList.toggle('expand')
});
#one {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100vh;
  background-color: black;
  top: -100vh;
  transition: all 1s;
  z-index: -1;
}

#one.expand {
  top: 0;
}
<button id="button">Click</button>

<div id="one"></div>

Upvotes: 3

Related Questions