Animation + Drag-and-Drop = Fun!

Drag-and-drop combined with animations are an incredibly powerful combination. Take a moment to review and experiment with the following block of code, which combines very basic concepts from drag-and-drop in the previous chapter with what you've been learning about in this one; it's illustrated in Figure 8-6.

A visualization of the x^5 easing function

Figure 8-6. A visualization of the x^5 easing function

<html>
    <head>
        <title>Animation + Drag and Drop = Fun!</title>

        <script
             type="text/javascript"
             src="http://o.aolcdn.com/dojo/1.1/dojo/dojo.xd.js">
        </script>
    <script type="text/javascript">
        dojo.require("dojo.fx");
        dojo.require("dojo.dnd.move");
        dojo.addOnLoad(function(  ){
          var move = new dojo.dnd.Moveable(dojo.byId("ball"));
          var coords;
          dojo.subscribe("/dnd/move/start",function(e){
            // when drag starts, save the coords
            coords = dojo.coords(e.node);
          });

          //now use the coords to control where the image slides back
          dojo.subscribe("/dnd/move/stop",function(e){
            dojo.fx.slideTo({
              node: e.node,
              top: coords.t,
              left: coords.l,
              duration:1200,
              easing : function(x) { return Math.pow(x,5);}
            }).play(  );
          });
       });
    </script>
    </head>
    <body>
        <!-- Insert any image into the page here in place of ball.png -->
        <img style="position : absolute; left : 300px; top : 300px;"
                  id="ball"
               src="ball.png"/>
   </body>
</html>

To summarize, the code example detects the start of a global drag event and remembers the coordinates of where that drag began. Then, it waits until the drag event ends, and at that point, moves the image back to its original sport according to the specific easing function. The easing function dictates that the move back will be slow at first, but will rapidly accelerate toward the end in a trendy sort of way.

Get Dojo: The Definitive Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.