CookieEater
CookieEater

Reputation: 2496

Change color for some seconds using only CSS

Is it possible to change the color of a div on hover for X seconds, then return to its original color using only CSS?

I do not want any fade ins or outs between the color. For example, if I want to change the color of the div to yellow for 1 second on hover, it must remain yellow for 1 second, then immediately return to the original color.

This (http://jsfiddle.net/hZ49y/1/) is what I have so far. It works as I described above, but I feel that this way of using animation is not intuitive and hard to understand. Should I stick to using JavaScript for this purpose? What are some alternatives?

Upvotes: 6

Views: 12878

Answers (3)

António Almeida
António Almeida

Reputation: 10087

It is possible, but requires some math!

Here is the Fiddle

You must use another parameter of animation: animation-iteration-count as 1

div:hover {
    animation: myfirst 2s 1;
}

@keyframes myfirst
{
    0%      {background:red;}
    25%     {background:yellow;}
    75%     {background:yellow;}
    100%    {background:red;}
}

This is going to perform a 4s animation with the following "key-frames":

0s > red
1s > yellow (stays 2 seconds here)
3s > yellow
4s > red

The only problem is that the animation stops on mouse out. But you can use javascript to activate the animation (by toggle a class), so the animation doesn't stops on mouse out.


Update:

Here is a Fiddle with js to control css animation.

Upvotes: 8

PurkkaKoodari
PurkkaKoodari

Reputation: 6809

I got this with animation. It works exactly as you asked, the only problem is that after page load the box is yellow for a second.

http://jsfiddle.net/4TcMP/1/

Upvotes: 0

Barney
Barney

Reputation: 16456

CSS animations don't explicitly allow instantaneous, non-transitioning changes from frame-to-frame, but you can achieve the effect in practice by setting keyframes so close to each other that it's practically impossible for an intervening frame to come in (forked jsFiddle):

@keyframes myfirst
{
0%      {background:yellow;}
99.999% {background:yellow;}
100%    {background:red;}
}

Upvotes: 3

Related Questions