Friday, January 13, 2012

Lesson 2: Stacking jQuery animations

I feel like making it also a hands-on illustrated introduction to CoffeeScript. But don't forget to check the language overview and coding kickstarter at coffeescript.org, cause it's by far the best. jQuery lets you stack animation calls. So, when you want to perform sequential animations on the same page element, one by one, you have a neat interface right for the task!

Every animation call returns an object that also has 'animate' function. Append animation calls one after another, just the way you want them run. Here's the code:


Let's stack some more. Use more lines if required, don't forget indentation if you do:


CoffeeScript is a modern programming language, outdated programming techniques like code duplication should be avoided. Fortunately, keeping code slim is quite easy, let's define a function:


Find full sample code behind the link below, save it as html (or clone from github) and play around! (Be careful with auto-formatting in your editor - after inserting code, make sure indentation is preserved)

Source code links:

Move on to the next lesson!


2 comments :

  1. Hey Utgarda,
    I tried this example Exactly as is, but i'm not able to make it work

    Here is My Coffee file
    $j = jQuery
    $j('#ani2_btn1').click ->
    $j('#ani2_worm_bar')
    .animate(width:78).animate(left:'+=40',width:38)

    It generates to
    (function() {
    var $j;

    $j = jQuery;

    $j('#ani2_btn1').click(function() {
    return $j('#ani2_worm_bar').animate({
    width: 78
    }).animate({
    left: '+=40',
    width: 38
    });
    });

    }).call(this);


    Please help me where I'm going wrong

    ReplyDelete
    Replies
    1. Hi Kuldeep, your translated JS seems ok. The example works if you have 'ani2_btn1' and 'ani2_worm_bar' elements defined in html. To see the example working, download it and open with your browser, then change it to continue your experiments!

      Delete