How to activate CSS3 animation (webkit) using javascript?

Im really stuck. I want the CSS animation that I created (below) to activate when I click on the div. The only way I could do this was to use javascript to create the onClick event. However, I don't know how to run the / refrence animation, which is in my css file. Can anybody help me?

This is the animation in my css file that I want to run by clicking on the div.

@-webkit-keyframes colorchange { 0% { background-color: red; opacity: 1.0; -webkit-transform: scale(1.0) rotate(0deg); } 33% { background-color: blue; opacity: 0.75; -webkit-transform: scale(1.1) rotate(-5deg); } 67% { background-color: green; opacity: 0.5; -webkit-transform: scale(1.1) rotate(5deg); } 100% { background-color: red; opacity: 1.0; -webkit-transform: scale(1.0) rotate(0deg); } } 

I even tried putting css in the same file as javascript (index.html), and used the following code to try to activate it when clicked, but no luck.

 <script> function colorchange( test ) { test.style.webkitAnimationName = 'colorchange '; } </script> 

Please, help:)

+7
javascript css
source share
1 answer

You are short of duration, and you have a finite space in the name that you assign:

 function colorchange( test ) { test.style.webkitAnimationName = 'colorchange'; // you had a trailing space here which does NOT get trimmed test.style.webkitAnimationDuration = '4s'; } 

Further information at @-webkit-keyframes :
http://webkit.org/blog/324/css-animation-2/

Update

Some work codes.

 <html> <head> <style> @-webkit-keyframes colorchange { 0% { background-color: red; opacity: 1.0; -webkit-transform: scale(1.0) rotate(0deg); } 33% { background-color: blue; opacity: 0.75; -webkit-transform: scale(1.1) rotate(-5deg); } 67% { background-color: green; opacity: 0.5; -webkit-transform: scale(1.1) rotate(5deg); } 100% { background-color: red; opacity: 1.0; -webkit-transform: scale(1.0) rotate(0deg); } } </style> <script> function colorchange(e) { if (e.style.webkitAnimationName !== 'colorchange') { e.style.webkitAnimationName = 'colorchange'; e.style.webkitAnimationDuration = '4s'; // make sure to reset the name after 4 seconds, otherwise another call to colorchange wont have any effect setTimeout(function() { e.style.webkitAnimationName = ''; }, 4000); } } </script> </head> <body> <div onclick="colorchange(this)">Hello World!</div> </body> </html> 
+11
source share

All Articles