It is a whole lot of an easier process to write a code of animation in CSS than in jquery. But the limitation with CSS is that it is not interactive. It can’t be invoked on a button click like it is done with jquery. But there is a trick of blending Javascript with CSS and invoke the CSS animation function with an onclick javascript function.
Here we will try to move an image horizontally to a distant on the click of a button. It’s not much of a tricky code. Feel free to copy and paste the following code. Here we go!
First the stylesheet:
.classname
{
width:320px;
height:200px;
background:red;
animation:anyname 2s;
-moz-animation:anyname 2s; /* Firefox */
-webkit-animation:anyname 2s; /* Safari and Chrome */
animation-direction:alternate;
-moz-animation-direction:alternate;
-webkit-animation-direction:alternate;
animation-timing-function:linear;
-moz-animation-timing-function:linear; /* Firefox */
-webkit-animation-timing-function:linear; /* Safari and Chrome */
}
@keyframes anyname
{
from {margin-left:0px;}
to {margin-left:600px;}
}
@-moz-keyframes anyname /* Firefox */
{
from {margin-left:0px;}
to {margin-left:600px;}
}
@-webkit-keyframes anyname /* Safari and Chrome */
{
from {margin-left:0px;}
to {margin-left:600px;}
}
The Javascript:
function ani(){
document.getElementById('something').className ='classname';
}
At last the HTML:
<input name="" type="button" value="Change" onclick="ani()" />
How does it work:
The HTML marksup a picture, and button clicking which the function ani() runs which is defined in the Script written above inside head. In function ani() it is instructed to get the element with id=”something”. In HTML part there is a division with that id so its been called by the script. Now the code is inserting a class called classname into the division which is defined above in the CSS with all the information about the animations. So as soon as the button is clicked the function ani() is called and it invokes a class with animation properties into the division where id=”something”.