Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger animation on element click in pure CSS

Let's say I have a simple element:

<a href="#" id="btn" onclick="return false">Click</a>

Now I can change the look of this element on click via :active:

#btn:active {
    background: red;
}

What I'd like however is that the element will stay red for about a second after I clicked it without altering the HTML (so no checkbox hack) or javascript. Is there a smart trick that can be abused for this?

JsFiddle here

like image 767
Jan Jongboom Avatar asked Aug 22 '13 09:08

Jan Jongboom


People also ask

How do you trigger a click in CSS?

You can use CSS3 animations and trigger with the :focus & :active ... Now, you can activate the effect with just pressing the TAB key... If you can use another object, let say an input type="text" then the focus it's automaticly set when you do the click , but in this case the focus action it's given by the browser.

How do I make a click animation?

Go to Animations > Advanced Animation > Add Animation and select the animation you want to add. Next, go to Animations > Advanced Animation > Animation Pane. In the Animation Pane, select the animated shape or other object that you want to trigger to play when you click it.

How do I delay an animation in CSS?

The CSS animation-delay property has the following syntax: animation-delay: [time] | initial | inherit; As you can see, there are three possible values: time, initial, and inherit. The first option is [time], which is the number of seconds or milliseconds before the animation starts.


1 Answers

Answering my own question. By abusing the :not pseudo class we can trigger an animation after a onclick happened:

#btn:not(:active) {
    /* now keep red background for 1s */
    transition: background-color 1000ms step-end;
}

#btn:active {
    background: red;
}
like image 73
Jan Jongboom Avatar answered Nov 12 '22 17:11

Jan Jongboom