GQuery Animations – how to use them

Animations are very popular and often used by web designers while creating web pages. I have covered the basics of GWT Animation in my old post. The topic seems  easy and worn-out, but I am still getting a lot of questions about using animations in GWT. That is why I  wrote some words about newest approach for animating DOM elements in modern web applications.

Animation – Abstract

Modern web applications as well as web pages are tending to be more and more user-friendly. Having intuitive interfaces, better accessibility, being more interactive and also more beautiful.  They are getting more dynamic too, the content is changing a lot. We can remove, add, update elements in the DOM – which provides instant interactions to user actions. Such dynamic changes are very often “smoothed” with animation effects. So instead of removing element at once – we can use “fade in” animation, instead of hoping from one page section to another – we can have “smooth scroll” effect, instead of rapid color change from red to blue – we can blend the transition. In many cases it feels more natural and convenient to the end-user.

opacitychage

In my opinion, we like such smooth effects because in many real world scenarios real objects do not disappear or change so promptly (maybe only in the circus;) ). When an object moves from place x(1) to  x(n) it is not happening in the blink of an eye, but the move is distributed in the time and space and we can see several positions of that object ( x(2), x(3), … x(n-1) (moving cloud). Same applies to color changes (sunset), size changes(blow balloon), etc.  Bringing those natural real live elements to the computer world, makes user feel save and secure.
 

Animation – technical point of view

In my old post about GWT Animations I have shown how to write simple animations, which are used to change some of the DOM properties in a smooth way, eg changing the size of a Label (http://blog-demo.appspot.com/#animation).

Since that time many lines of code have been written and many new ideas and features regarding that topic have come along.  For instance, one of the modern ways of doing animations in web applications would be using CSS3 Animations. There are many useful tools which help you to create your own animations, eg : css3-maker, ceaser  and many others.

Anyhow in this post I will cover the programatical way of animating DOM elements. But as you will find in next section, achieving it with GQuery is very simple. If you are familiar with JQuery it will come even more easy.

GQuery Animations

GQuery is a modern and handy framework, which can help you build your GWT-based applications. Quoting GQuery page:

“GQuery is a jQuery-like API written in GWT, which allows GWT to be used in progressive enhancement scenarios where perhaps GWT widgets are too heavyweight”

Among many cool features of JQuery (fast selectors, easy dom manipulation, etc) you will also find support for animations.

Simple example

Enough writing, let’s see some moving things. Take a look at this demo: demo. Resizing this label was accomplished with code shown here : GWT Code. The significant lines from that example are:

//1 Declaring Animation
public class ResizeWidthAnimation  extends Animation {
        // initial size of widget
        private int startWidth = 0;
        // desired size of widget. Widget will have this size after animation will stop to run
        private int desiredWidth = 0;
       public ResizeWidthAnimation(int desiredWidth) {
            this.startWidth = resizedWidget.getOffsetWidth();
            this.desiredWidth = desiredWidth;
        }
        @Override
        protected void onUpdate(double progress) {
            double width = extractProportionalLength(progress) ;
            resizedWidget.setWidth( width + Unit.PX.getType());
        }
        private double extractProportionalLength(double progress) {
            double outWidth = startWidth - (startWidth - desiredWidth) * progress;
            return outWidth;
        }
    }

 

//2 Running the Animation
 ResizeWidthAnimation resizeAnimation = new ResizeWidthAnimation(DESIRED_WIDGET_WIDTH);
 resizeAnimation.run(DURATION);

Doing same animation using GQuery would look like this:

GQuery.$(resizedWidget).animate("width:" + DESIRED_WIDGET_WIDTH + Unit.PX.getType(), DURATION);

Isn’t that simple? On the top of that I can mention that the animate() function is very generic and allows you to animate change of many css properties. Beeing precise I will quote the api:

The animate() method allows you to create animation effects on any numeric  Attribute, CSS property, or color CSS property.

Exploring powers of GQuery animations

Let’s see other examples presenting capabilities of GQuery animations. You can see all presented examples working on the: demo page.

Parallel animations

If You want to animate multiple properties of an DOM element at once,  you can do it by simply placing the desired transitions in a coma separated list:


$(changeMe).animate("color:'darkcyan', width:400px, border-width:10px");

This code will change color of the label to dark cyan, at the same time changing its width to 400px and border width to 10px. It will happen in default time which is 400 milliseconds.

onComplete callback function

If you need to run any code just right after the animation was finished, you can add function call to the animate() function parameter’s list:

$(changeMe).animate("color:'darkcyan', width:400px, border-width:10px", 1000,
 new com.google.gwt.query.client.Function() {
   public void f(Element e) {
     resetButton.setEnabled(true);
   }
});

Queueing Animations

You can also run animations one after another adding them to a queue. You can also specify delays which will cause the animations to wait specified amount of time.

$(changeMe).animate("background-color:'darkmagenta", 500).delay(50)
        .animate("background-color:'darkred'", 500).delay(150)
        .animate("background-color:'orange'", 500).delay(150)
        .animate("background-color:'green'", 500);

This code will change background color to dark magenta, wait 50 milliseconds, then change background to dark red, wait 150 milliseconds, and so on.

Configurable Easing (interpolate)

You can also create your own Easing function (which is equivalent of GWT Animation.interpolate()). This will allow you to control the progress ( and also the instantaneous velocity of your animation)

Easing myEasing = new Easing() {
  @Override
  public double interpolate(double progress) {
    return progress*( 1.0 - progress )*4.0;
  }
};

$(changeMe).animate("left:'500px'", 1500, myEasing) ;

This code will move the label to the right, and then make it come back to the starting position.

Animation in a loop

If you need to run continuous animation, you can define a recurrent call in “on complete” callback function.

@UiField
Button button;

@UiField
Button resetButton;

@UiField
Image ballImage;

/**
 * reference to animation is hold as a field,
 * so it can be started and stopped when needed
 */
 GQuery animation;

/**
 * stop the animation
 */
@UiHandler("resetButton")
public void onClickReste(ClickEvent event) {
  animation.stop();
}

/**
 * start the animation
 */
@UiHandler("button")
public void onClick(ClickEvent event) {
  $(ballImage).css("top", "0");
  run();
}

/**
 * run the animation in a loop
 */
public void run() {
  Easing comeBackEasing = new Easing() {

    @Override
    public double interpolate(double progress) {
      return -(progress * (1.0 - progress) * 2.0);
    }
  };

  animation = $(ballImage).animate("top:'200px'", 1500, comeBackEasing,
    new com.google.gwt.query.client.Function() {
      public void f(Element e) {
        // log.info("starting animation again");
        run();
      }
  });
}

Summary

As you can see in those simple examples, moving and changing DOM elements with GQuery is pretty simple. You can generate cool effects just in one line of code. The advantage of this solution is also its flexibility – you can combine animations with GQuery selectors. You are not bounded to any specific widget – since you can apply animations to any DOM element which has numeric HTML Attribute,  numeric CSS property, or color CSS property.

Links

GQuery – Getting started guide : https://code.google.com/p/gwtquery/wiki/GettingStarted

GQuery official page: https://code.google.com/p/gwtquery/

Advertisements

3 Responses to GQuery Animations – how to use them

  1. Pingback: GWT Animation – small review | My Fascinations

  2. Mansoor Ahamed I. says:

    Thanks for the post… 🙂

  3. Pingback: Marquee with GWT and GQuery | My Fascinations

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: