Fred K
Fred K

Reputation: 13910

Showing an hidden element with an opacity-animation

I've a #foo element hidden, and I need to show it with zoomIn css animation (that bring an element from opacity:0 to opacity:1.

This is the code I'm using:

CSS

#foo {
  opacity: 0;
  ...
}

// Zoom In animation
@keyframes zoomIn {
  0% {
    opacity: 0;
    transform: scale3d(.3, .3, .3);
  }
  50% {
    opacity: 1;
  }
}

.zoomIn {
  animation: zoomIn .2s ease-in-out 0s both;
}

JS

$(document).ready(function() {
    $("#foo").addClass("zoomIn");
});​

With the above code I see the animation and then the #foo element disappears again. It doesn't hold the opacity:1. How can solve it?

Upvotes: 0

Views: 128

Answers (2)

Alexis B.
Alexis B.

Reputation: 1115

About Keyframes

In complement to the post of Slugge, I was wondering why you end your animation at 50%. I think you should end it at 100% (especially if you want the opacity to stay at 1). Or instead of 0% {} 100% {}, you can use from {} to {}.

@keyframes zoomIn {
  0% {
    opacity: 0;
    transform: scale3d(.3, .3, .3);
  }
  100% {
    opacity: 1;
  }
}

About an other solution

I think it would be easier to just define a transition and an "active" class instead of using Keyframes.

#foo {
  opacity: 0;
  transition: opacity 0.2s ease-out;
}

#foo.active {
  transform: scale3d(.3, .3, .3);
  opacity: 1;
}

then

$(document).ready(function() {
    $("#foo").addClass("active");
});​

You could add the transition the transform as well with transition: opacity 0.2s ease-out, transform 0.2s ease-out; or with transition: all 0.2s ease-out;

Good Luck'

Upvotes: 1

Slugge
Slugge

Reputation: 180

You need to define what happends at the end of the animation, this can be done with "forwards" property of animation-fill-mode, this requires the animation to have an end (can not end on 50%, must end on 100% or from-to) so change:

.zoomIn {
    animation: zoomIn .2s ease-in-out 0s both;
}

to:

.zoomIn {
     animation: zoomIn .2s ease-in-out 0s forwards;
}

By using both, you say that the element should both use forwards and backwards, where forwards is the "end" of the animation, and backwards is the "beginning" of the animation. Therefor you will have opacity: 0 and opacity: 1, and apparently the backwards value is the stronger one of the two.

Upvotes: 1

Related Questions