CodingIntrigue
CodingIntrigue

Reputation: 78535

Immediately reverse CSS3 animation

When I add the .shown class to my #overlay I would like the opacity to fade in for 2secs, then immediately reverse and fade out for 2 seconds, creating a sort of "flashing" effect.

I tried just removing the class but that doesn't show any animation at all. This is my sample markup/CSS:

HTML:

<div id="outer">
    This is some text
    <div id="overlay"></div>
</div>

CSS:

#overlay {
    ...
    opacity: 0;
    transition: opacity 2s ease-in-out;
}
#overlay.shown {
    opacity: 0.3;
}

Attemped JS:

// Wait 2 seconds from page load...
setTimeout(function() {
    // Add shown class to trigger animation
    document.getElementById("overlay").classList.add("shown");
    // Want to remove the class and hoped this would reverse the animation...
    // it doesn't
    document.getElementById("overlay").classList.remove("shown");
}, 2000);

jsFiddle

Upvotes: 2

Views: 192

Answers (3)

Just code
Just code

Reputation: 13801

There are lots of changes i have done to achieve your out put please check following code

Your css
#outer {
    width: 100px;
    height: 100px;
    position: relative;
}
#overlay {
    top: 0;
    left: 0;
    position: absolute;
    width: 100%;
    height: 100%;
    background: #336699;
    opacity: 0;
    transition: opacity 2s ease-in-out;
}
#overlay.shown {
    display: block;
    opacity: 0.5;
}

Your js

setTimeout(function() {
    $("#overlay").addClass("shown");
   var def = $('#overlay').promise();
    def.done(
       function () {
          $('body').stop().delay(5000).queue(function(){
        $("#overlay").removeClass("shown");
    });

    });


}, 2000);

There was no delay between first and second so how it will show animation which you have done

Please check working demo.....Demo

Upvotes: 0

johntraver
johntraver

Reputation: 3612

It looks like you could use a second timeout after the first animation completes..

// Wait 2 seconds from page load...
setTimeout(function() {
    // Animate Forward
    document.getElementById("overlay").classList.add("shown");
    setTimeout(function(){
        // Animate Back
        document.getElementById("overlay").classList.remove("shown");
    },2000);
}, 2000);

Upvotes: 0

Taimour Tanveer
Taimour Tanveer

Reputation: 408

use css animation with keyframes

@keyframes myFlash
{
0%   {opacity:0;}
50%  {opacity:0.3;}
100% {opacity:0;}
}

@-webkit-keyframes myFlash /* Safari and Chrome */
{
0%   {opacity:0;}
50%  {opacity:0.3;}
100% {opacity:0;}
}

#overlay {
    ...
    opacity: 0;
}
#overlay.shown {
animation:myFlash 2s;
-webkit-animation:myFlash 2s; /* Safari and Chrome */
}

Upvotes: 2

Related Questions