Montag, 21. April 2014

[Web Development] The ways of animating stuff using JavaScript, JQuery and CSS

Because a co-worker asked me how to fade something in and out I thought about making a short overview on the techniques you can use to achieve animations. I will present you 3 ways how you could fade elements in and out.

The Plain JavaScript Way

DON'T DO IT. I tried this once. Took me about 8 hours to create kind of a translate animation but it still wasn't very smooth. Better use one of the two ways following.

The JQuery Way

After I did a JavaScript animation not knowing of JQuery, I have seen that you can create animations in JQuery within a single line.
$("div").fadeIn();
$("div").fadeOut();
$("div").fadeToggle();
JQuery even comes with a fadeToggle() method which will fade the element in if it is hidden at the moment and fade the element out if its visible.
Each of the presented methods have callbacks you can use like this
$("div").fadeIn("slow", function() {
    // Animation complete
});
Another way to achieve fading in JQuery is the following one but I don't really know why you should use this one.
//Will fade out the div in 5 seconds
$("div").animate({
    opacity: 0,
}, 5000, function() {
    //Will be executed after the animation
});

//Will fade in the div in 5 seconds
$("div").animate({
    opacity: 1,
}, 5000, function() {
    //Will be executed after the animation
});
To come to an end I present you my favorite way.

The CSS Way

CSS3 comes with the so called transitions. Each browser supporting CSS3 supports these animations. They are easy to implement and don't enlarge your JavaScript code. You can use it like this.
-webkit-transition: opacity 500ms ease-out 1s;
-moz-transition: opacity 500ms ease-out 1s;
-o-transition: opacity 500ms ease-out 1s;
transition: opacity 500ms ease-out 1s;
Now every change in the opacity of the element is animated. You just need to adjust the opacity using a single JQuery line like this
$("div").css("opacity", 0);
And all the magic is done now. Let me know your thinkings of the 3 ways and what are you using.
Have a good day :)

1 Kommentar: