Search code examples
javascriptcsscss-animationskeyframe

How to prevent css keyframe animation on page load?


I have some CSS animation with keyframes on my page for fadein/out elements. The problem is that the fadeout animations are shown when i load the page.

HTML:

<button class="toggle-good">Toggle display</button>
<p class="box">I move nicely!</p>

CSS:

.box {
  height: 0;
  opacity: 0;
  animation: FadeOut 1s ease-in-out;
}
.box.active {
  height: initial;
  opacity: 1;
  animation: FadeIn 1s ease-in-out;
}
@keyframes FadeIn {
  0% {
    opacity: 0;
    height: initial;
  }
  100% {
    opacity: 1;
    height: initial;
  }
}
@keyframes FadeOut {
  0% {
    opacity: 1;
    height: initial;
  }
  99% {
    opacity: 0;
    height: initial;
  }
  100% {
    height: 0;
    opacity: 0;
    height: 0;
  }
}

JS:

$('button').on('click', function(e) {
  $(this).siblings('.box').toggleClass('active');
})

Working example: http://codepen.io/MickL/pen/LkvWaA


Solution

  • All you should need to do is: animation-play-state: paused;

    However, having a look at your codepen, keyframe animations probably aren't your best best. It looks like you're just using the keyframes to ensure some of your properties only change at the end of the animation. Luckily, there's actually a transition timing function for this!

    1. Use transition property, using step-end and step-start for visibility and pointer-events.
    2. Pointer events used to prevent interaction with a hidden element.
    3. Max-height used to remove the object from document flow when hidden.

    I've spun together a quick code pen to show an example.

    http://codepen.io/SudoCat/pen/LkvyEJ?editors=0100