Tuesday, May 20, 2014

Back to Basics - Understanding How JQuery Animate Works

It occurred to me that I should scale back just a bit to help break down the basics of my favorite JQuery feature - the animation. You'll see this come up a lot in my write-ups, as this is such a simple, yet incredibly powerful feature. It calculates and literally "plays out" the difference between a start point and end point, which is not just limited to page locations. To begin, the following items are needed

  • Reference to JQuery library in the header (Latest is currently v 1.11.1)
    • <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.js"></script>
  • Method to invoke the function (Can be bound to whatever handler, such as onLoad, onClick, etc., using JQuery or plain Javascript)
    • function animateThis()
    • {
    • $('#myDiv').animate({
    •    opacity:'0.0',
    •    },1024,function(){doMore())}
    • );
    • }
  • A container to be animated (Div works best)
    • <div id="myDiv">This container will be animated using my parameters</div>


Now, to break down the animate method.


  • $('#myDiv') tells JQuery which element or container ID to animate (Match to the "id" attribute). 
  • .animate tells JQuery to use the "animate" method and perform it
  • ({opacity:'0.0',} tells JQuery which options to use for the animation math. I'm using opacity as example in this case, which, currently set to "0.0", instructs JQuery to animate myDiv from it's current opacity to 0% opacity (invisible). This can be set to different levels, such as "0.5", which would be 50% opaque - put another way, half transparent. The effect for this example is that the contents of myDiv would fade into nothing and disappear. 
    • Many CSS attributes can be used to animate, using any combination there-of
      • Positions can be used (margin-left, left, top, bottom, etc.) - *Interestingly right and margin-right are not supported
      • Sizing can be used (height, width, etc.)
  • 1024, tells JQuery how long the animation should take to finish out, in milliseconds (1024 ms = 1 second)
  • function(){doMore())}tells JQuery to call a new function at the completion of the animation (this is totally optional and can be omitted, if not needed)
That's it! Give it a try!

No comments:

Post a Comment