Reputation: 1541
Can I start a css animation onclick
and then reverse it when clicked again?
I just want it to switch between the two states. How can I do this?
Do I need to use JavaScript?
Upvotes: 2
Views: 1947
Reputation: 7097
You can absolutely do this. Personally, I think that it's easiest to do with JavaScript, but there are other ways around this. Although JS can be quite ugly, one of the beautiful things about it is the ability to use closures. Closures allow for a function to maintain the state of a variable after it goes out of scope. This can allow you to keep the state of a variable for tracking purposes, such as checking to see if the element was previously clicked.
Your question does not show any code so I'm not completely sure how you wrote your animations in CSS, but lets assume that you're using CSS3 transitions that are declared in some classes. Also, my example is going to use jQuery because I find it much easier to use.
Let's say that we have a transition or animation declared in a class named oddAnimation
and the reverse of that transition/animation in another class named evenAnimation
. Additionally, the element that we're going to add the onclick handler to will have the id of "mybutton".
$(document).ready(function() {
var clicked = false;
$('#mybutton').click(function() {
if(clicked) {
clicked = false;
$(this).removeClass('oddAnimation').addClass('evenAnimation');
}
else {
clicked = true;
$(this).removeClass('evenAnimation').addClass('oddAnimation');
}
});
});
This code creates an onclick handler for the element with the id of "mybutton" and a variable for tracking named clicked that we will toggle each time the handler's callback is run. This handler will also change the classes on that element to activate the proper transitions/animations on click.
Keep in mind that this all assumes everything is set up in your CSS within classes. There are other ways to do this using only JavaScript (and no CSS animations/transitions) or to activate the animations differently, but this method may do the trick for you.
Upvotes: 1