jQuery API

.animate()

.animate( properties [, duration] [, easing] [, complete] ) Returns: jQuery

Description: Perform a custom animation of a set of CSS properties.

  • version added: 1.0.animate( properties [, duration] [, easing] [, complete] )

    propertiesA map of CSS properties that the animation will move toward.

    durationA string or number determining how long the animation will run.

    easingA string indicating which easing function to use for the transition.

    completeA function to call once the animation is complete.

  • version added: 1.0.animate( properties, options )

    propertiesA map of CSS properties that the animation will move toward.

    optionsA map of additional options to pass to the method. Supported keys:

    • duration: A string or number determining how long the animation will run.
    • easing: A string indicating which easing function to use for the transition.
    • complete: A function to call once the animation is complete.
    • step: A function to be called after each step of the animation.
    • queue: A Boolean indicating whether to place the animation in the effects queue. If false, the animation will begin immediately. As of jQuery 1.7, the queue option can also accept a string, in which case the animation is added to the queue represented by that string.
    • specialEasing: A map of one or more of the CSS properties defined by the properties argument and their corresponding easing functions (added 1.4).

The .animate() method allows us to create animation effects on any numeric CSS property. The only required parameter is a map of CSS properties. This map is similar to the one that can be sent to the .css() method, except that the range of properties is more restrictive.

Animation Properties and Values

All animated properties should be animated to a single numeric value, except as noted below; most properties that are non-numeric cannot be animated using basic jQuery functionality (For example, width, height, or left can be animated but background-color cannot be, unless the jQuery.Color() plugin is used). Property values are treated as a number of pixels unless otherwise specified. The units em and % can be specified where applicable.

In addition to style properties, some non-style properties such as scrollTop and scrollLeft, as well as custom properties, can be animated.

Shorthand CSS properties (e.g. margin, background, border) are not supported. For example, if you want to retrieve the rendered margin, use: $(elem).css('marginTop') and $(elem).css('marginRight'), and so on.

In addition to numeric values, each property can take the strings 'show', 'hide', and 'toggle'. These shortcuts allow for custom hiding and showing animations that take into account the display type of the element.

Animated properties can also be relative. If a value is supplied with a leading += or -= sequence of characters, then the target value is computed by adding or subtracting the given number from the current value of the property.

Note: Unlike shorthand animation methods such as .slideDown() and .fadeIn(), the .animate() method does not make hidden elements visible as part of the effect. For example, given $('someElement').hide().animate({height:'20px'}, 500), the animation will run, but the element will remain hidden.

Duration

Durations are given in milliseconds; higher values indicate slower animations, not faster ones. The strings 'fast' and 'slow' can be supplied to indicate durations of 200 and 600 milliseconds, respectively.

Complete Function

If supplied, the complete callback function is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but this is set to the DOM element being animated. If multiple elements are animated, the callback is executed once per matched element, not once for the animation as a whole.

Basic Usage

To animate any element, such as a simple image:

<div id="clickme">
  Click here
</div>
<img id="book" src="book.png" alt="" width="100" height="123"
  style="position: relative; left: 10px;" />

To animate the opacity, left offset, and height of the image simultaneously:

$('#clickme').click(function() {
  $('#book').animate({
    opacity: 0.25,
    left: '+=50',
    height: 'toggle'
  }, 5000, function() {
    // Animation complete.
  });
});

Note that the target value of the height property is 'toggle'. Since the image was visible before, the animation shrinks the height to 0 to hide it. A second click then reverses this transition:

The opacity of the image is already at its target value, so this property is not animated by the second click. Since the target value for left is a relative value, the image moves even farther to the right during this second animation.

Directional properties (top, right, bottom, left) have no discernible effect on elements if their position style property is static, which it is by default.

Note: The jQuery UI project extends the .animate() method by allowing some non-numeric styles such as colors to be animated. The project also includes mechanisms for specifying animations through CSS classes rather than individual attributes.

Note: if attempting to animate an element with a height or width of 0px, where contents of the element are visible due to overflow, jQuery may clip this overflow during animation. By fixing the dimensions of the original element being hidden however, it is possible to ensure that the animation runs smoothly. A clearfix can be used to automatically fix the dimensions of your main element without the need to set this manually.

Step Function

The second version of .animate() provides a step option — a callback function that is fired at each step of the animation. This function is useful for enabling custom animation types or altering the animation as it is occurring. It accepts two arguments (now and fx), and this is set to the DOM element being animated.

  • now: the numeric value of the property being animated at each step
  • fx: a reference to the jQuery.fx prototype object, which contains a number of properties such as elem for the animated element, start and end for the first and last value of the animated property, respectively, and prop for the property being animated.

Note that the step function is called for each animated property on each animated element. For example, given two list items, the step function fires four times at each step of the animation:

$('li').animate({
  opacity: .5,
  height: '50%'
},
{
  step: function(now, fx) {
    var data = fx.elem.id + ' ' + fx.prop + ': ' + now;
    $('body').append('<div>' + data + '</div>');
  }
});

Easing

The remaining parameter of .animate() is a string naming an easing function to use. An easing function specifies the speed at which the animation progresses at different points within the animation. The only easing implementations in the jQuery library are the default, called swing, and one that progresses at a constant pace, called linear. More easing functions are available with the use of plug-ins, most notably the jQuery UI suite.

Per-property Easing

As of jQuery version 1.4, you can set per-property easing functions within a single .animate() call. In the first version of .animate(), each property can take an array as its value: The first member of the array is the CSS property and the second member is an easing function. If a per-property easing function is not defined for a particular property, it uses the value of the .animate() method's optional easing argument. If the easing argument is not defined, the default swing function is used.

For example, to simultaneously animate the width and height with the swing easing function and the opacity with the linear easing function:

$('#clickme').click(function() {
  $('#book').animate({
    width: ['toggle', 'swing'],
    height: ['toggle', 'swing'],
    opacity: 'toggle'
  }, 5000, 'linear', function() {
      $(this).after('<div>Animation complete.</div>');
  });
});

In the second version of .animate(), the options map can include the specialEasing property, which is itself a map of CSS properties and their corresponding easing functions. For example, to simultaneously animate the width using the linear easing function and the height using the easeOutBounce easing function:

$('#clickme').click(function() {
  $('#book').animate({
    width: 'toggle',
    height: 'toggle'
  }, {
    duration: 5000,
    specialEasing: {
      width: 'linear',
      height: 'easeOutBounce'
    },
    complete: function() {
      $(this).after('<div>Animation complete.</div>');
    }
  });
});

As previously noted, a plugin is required for the easeOutBounce function.

Additional Notes:

  • All jQuery effects, including .animate(), can be turned off globally by setting jQuery.fx.off = true, which effectively sets the duration to 0. For more information, see jQuery.fx.off.
  • Because of the nature of requestAnimationFrame(), you should never queue animations using a setInterval or setTimeout loop. In order to preserve CPU resources, browsers that support requestAnimationFrame will not update animations when the window/tab is not displayed. If you continue to queue animations via setInterval or setTimeout while animation is paused, all of the queued animations will begin playing when the window/tab regains focus. To avoid this potential problem, use the callback of your last animation in the loop, or append a function to the elements .queue() to set the timeout to start the next animation.

Examples:

Example: Click the button to animate the div with a number of different properties.

<!DOCTYPE html>
<html>
<head>
  <style>
div {
background-color:#bca;
width:100px;
border:1px solid green;
}
</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <button id="go">&raquo; Run</button>

<div id="block">Hello!</div>
<script>

/* Using multiple unit types within one animation. */

$("#go").click(function(){
  $("#block").animate({
    width: "70%",
    opacity: 0.4,
    marginLeft: "0.6in",
    fontSize: "3em",
    borderWidth: "10px"
  }, 1500 );
});
</script>

</body>
</html>

Demo:

Example: Animates a div's left property with a relative value. Click several times on the buttons to see the relative animations queued up.

<!DOCTYPE html>
<html>
<head>
  <style>
div {
  position:absolute;
  background-color:#abc;
  left:50px;
  width:90px;
  height:90px;
  margin:5px;
}
</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <button id="left">&laquo;</button> <button id="right">&raquo;</button>
<div class="block"></div>

<script>
$("#right").click(function(){
  $(".block").animate({"left": "+=50px"}, "slow");
});

$("#left").click(function(){
  $(".block").animate({"left": "-=50px"}, "slow");
});

</script>

</body>
</html>

Demo:

Example: The first button shows how an unqueued animation works. It expands the div out to 90% width while the font-size is increasing. Once the font-size change is complete, the border animation will begin. The second button starts a traditional chained animation, where each animation will start once the previous animation on the element has completed.

<!DOCTYPE html>
<html>
<head>
  <style>
div {
  background-color:#bca;
  width:200px;
  height:1.1em;
  text-align:center;
  border:2px solid green;
  margin:3px;
  font-size:14px;
}
button {
  font-size:14px;
}
</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <button id="go1">&raquo; Animate Block1</button>
<button id="go2">&raquo; Animate Block2</button>
<button id="go3">&raquo; Animate Both</button>

<button id="go4">&raquo; Reset</button>
<div id="block1">Block1</div>
<div id="block2">Block2</div>
<script>

$( "#go1" ).click(function(){
  $( "#block1" ).animate( { width: "90%" }, { queue: false, duration: 3000 })
     .animate({ fontSize: "24px" }, 1500 )
     .animate({ borderRightWidth: "15px" }, 1500 );
});

$( "#go2" ).click(function(){
  $( "#block2" ).animate({ width: "90%" }, 1000 )
     .animate({ fontSize: "24px" }, 1000 )
     .animate({ borderLeftWidth: "15px" }, 1000 );
});

$( "#go3" ).click(function(){
  $( "#go1" ).add( "#go2" ).click();
});

$( "#go4" ).click(function(){
  $( "div" ).css({ width: "", fontSize: "", borderWidth: "" });
});

</script>

</body>
</html>

Demo:

Example: Animates the first div's left property and synchronizes the remaining divs, using the step function to set their left properties at each stage of the animation.

<!DOCTYPE html>
<html>
<head>
  <style>
div {
   position: relative;
   background-color: #abc;
   width: 40px;
   height: 40px;
   float: left;
   margin: 5px;
}
</style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  
<p><button id="go">Run »</button></p>
<div class="block"></div> <div class="block"></div>
<div class="block"></div> <div class="block"></div>
<div class="block"></div> <div class="block"></div>

<script>
$( "#go" ).click(function(){
  $( ".block:first" ).animate({
    left: 100
  }, {
    duration: 1000,
    step: function( now, fx ){
      $( ".block:gt(0)" ).css( "left", now );
    }
  });
});
</script>

</body>
</html>

Demo:

Example: Animates all paragraphs to toggle both height and opacity, completing the animation within 600 milliseconds.

$( "p" ).animate({
  "height": "toggle", "opacity": "toggle"
}, "slow" );

Example: Animates all paragraph to a left style of 50 and opacity of 1 (opaque, visible), completing the animation within 500 milliseconds.

$( "p" ).animate({
  "left": "50", "opacity": 1
}, 500 );

Example: An example of using an 'easing' function to provide a different style of animation. This will only work if you have a plugin that provides this easing function. Note, this code will do nothing unless the paragraph element is hidden.

$( "p" ).animate({
  "opacity": "show"
}, "slow", "easein" );

Example: Animates all paragraphs to toggle both height and opacity, completing the animation within 600 milliseconds.

$( "p" ).animate({
  "height": "toggle", "opacity": "toggle"
}, { duration: "slow" });

Example: Animates all paragraph to a left style of 50 and opacity of 1 (opaque, visible), completing the animation within 500 milliseconds. It also will do it outside the queue, meaning it will automatically start without waiting for its turn.

$( "p" ).animate({
  left: "50px", opacity: 1
}, { duration: 500, queue: false });

Example: An example of using an 'easing' function to provide a different style of animation. This will only work if you have a plugin that provides this easing function.

$( "p" ).animate({
  "opacity": "show"
}, { "duration": "slow", "easing": "easein" });

Example: An example of using a callback function. The first argument is an array of CSS properties, the second specifies that the animation should take 1000 milliseconds to complete, the third states the easing type, and the fourth argument is an anonymous callback function.

$( "p" ).animate({
  height:200, width:400, opacity: .5
}, 1000, "linear", function(){ alert("all done"); });

Support and Contributions

Need help with .animate() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to .animate()? Report it to the jQuery core team.

Found a problem with this documentation? Report it to the jQuery API team.

* All fields are required
  • http://www.tmg-clan.com/ Roelof

    I sometimes have problems when using “animate()” with opacity.

    It worked for me again when I made it a fixed (or at least set) width (either px, em or %)

    PS: The new interface is a bit getting used to but the search is great (as is the CSS3 lay-out)!

  • Chionsas

    not with a default setup.
    you'll need http://plugins.jquery.com/project/color to do that.

    you could also possibly use some clever css trickery and fadeIn(), depending on circumstances :)

  • jtnix

    Color animation is also provided with jQueryUI http://jqueryui.com

  • http://twitter.com/paul_irish Paul Irish

    In jQuery Core there is only `swing` and `linear` easing.
    In the easing plugin (and in jquery UI) there are many more.. Preview them here:
    http://james.padolsey.com/demos/jquery/easing/

  • Anonymous

    can i add z-index with animate like below?
    $marginLefty.animate({ “z-index”:-1 }

  • Anonymous

    I believe you cant, however you have a few options,

    this would change the css property once the animation was finished (which i believe is probably what you are after):
    $marginLefty.animate({color: ‘red’},500, function(){
    $(this).css(‘zIndex’,'-1′)
    })

    or you could do this one which would change the z-index before the animation:
    $marginLefty.css(‘zIndex’,'-1′).animate({color:’red’},500)

    Remember you have to use camel case for the css properties that usually have a dash in them i.e. background-color changes to backgroundColor

  • Guest

    So what properties can you animate? There’s no list. Am I supposed to guess at what and with what name…? Since, of course, marginLeft the same as the actual CSS property.

  • michael gociu

    Is there any way to stop the animate() function while runing ?
    I was thinking to send a step parameter (step: A function to be called after each step of the animation.) which checks for certain conditions after each step of the animation, and somehow stops the animation if those conditions are met.

  • Anonymous

    If i set:

    $(“#show”).animate({
    width: “20%”,
    }, 800 );

    how can i make, that the #show will be minimizing to LEFT! not to right…

  • http://lowco.com/ Paul Lorentzen

    take a look at jpnwd’s issue above. An adaptation of his solution should work for you too.

    PS: The example code is very verbose for illustration purposes. In usage, you can put most of the math in the jQuery statement. ie:
    $(“#image0″).animate({ width:$(“#image0″).width() + 50, “margin-top”:’-=’+($(“#image0″).height()*50/$(“#image0″).width())/2, “margin-left”:’-=’+50/2 }, 1000 )

  • http://lowco.com/ Paul Lorentzen

    Is there a way to parameterize the css selector name? I would like to do something like this:

    $(“i”).animate({ “margin”+left_top : “‘”+directionOfTopMovement+”‘+”movementAmount}, 1000, “swing”);

    The parameters work for the value side of the css property, but I can’t figure out how to make it work on the selector side.

  • http://www.learningjquery.com/ Karl Swedberg

    I’m not sure what values you’re using for the variables you have in there already, so I’m going to make some up for the example:

    var left_top = ‘Top’;
    var directionOfTopMovement = ‘+=’;
    var movementAmount = ’30px’;
    var props = {};
    props["margin" + left_top] = directionOfTopMovement + movementAmount;
    $(“i”).animate(props, 1000, “swing”);

    This could be cleaned up quite a bit, but the general idea is that you can use array notation to use variables for an object property.

  • http://lowco.com/ Paul Lorentzen

    Works like a charm — Thanks Karl.

    If the props object is setup as part of the animate command, I guess the interpreter does not evaluate the props object key string before executing the command, right?

  • http://web-bereiter.de/ Ingo Augsten

    You can use the callback function to chain desired animation steps one after another, instead of interfering with one animation.

  • marlo

    use stop()

  • http://twitter.com/robcolburn Rob Colburn

    I had a similar issue, you may just need to stop “queue”

    Assume 2 divs

    And a simple hover script
    $(“#a”).hover(
    function(){ $(“#b”).animate({height:200}) }
    ,function(){ $(“#b”).animate({height:0}) }
    );

    We may want these animations to stop each other, so that they can run, but our real problem is the queue, which we can turn off.

    $(“#a”).hover(
    function(){ $(“#b”).animate({height:200},{queue:false}) }
    ,function(){ $(“#b”).animate({height:0},{queue:false}) }
    );

  • David

    can you animate the color or background-color?

  • http://www.learningjquery.com/ Karl Swedberg

    As noted, “The jQuery UI project extends the .animate() method by allowing some non-numeric styles such as colors to be animated. The project also includes mechanisms for specifying animations through CSS classes rather than individual attributes.”

  • http://twitter.com/loudnate Nate Racklyeft

    It's worth noting that properties such as scrollLeft and scrollTop are supported in addition to CSS properties.

  • RBully

    Correct me if I am wrong but all these questions should be asked in the appropriate forums.
    Like above mentioned “Please do post corrections or additional examples for .animate() below. We aim to quickly move corrections into the documentation.”

  • http://www.jklir.net/ Unreal][

    Don't use!:
    $('#foo').animate({ padding: “5px 2px 0 0″ }, 1000); // 1, 2, 3 and 4 parts setting

    Use separated padding, margin etc.:
    $('#foo').animate({ paddingTop: “5px”, paddingRight: “2px” }, 1000);

    The first example is treated as css() function and in IE6 returns error. The second example is now behaving correctly in all browsers.

  • just_jake

    A list of what can and cannot be animated by the standard .animate() function would be very useful.

  • http://www.haykranen.nl/ huskyr

    Not yet, but in the meantime you could try the color plugin: http://plugins.jquery.com/project/color

  • Caine

    It would be good to mention that if you want to move objects, their position must be set to absolute!

  • Jørgen Johanson

    The first demo (“Click the button to animate the div with a number of different properties”) does not seem to work as it should in IE8 (nothing happens when clicking the button). Works OK in FF3.6.3, Safari 4.0.5 and Opera 10.53.

  • http://www.learningjquery.com/ Karl Swedberg

    Well, we do mention that “The position attribute of the element must not be static if we wish to animate the left property as we do in the example.” That goes for the top property, too. It's sort of a truism that since the default position of elements is static, you can't move them unless you change their position property: Static things are unmoving by definition.

  • TheAnswerIs

    or you could say – “if you want to move objects, their position must be set to absolute!” , thanks .

    I agree that sometimes direct answers are the most efficient. You can always read more if you want to learn more.

  • http://openid-provider.appspot.com/fbogner fbogner

    Just if anyone is interested: Animations are “rendered” using a setInterval with a time out of 13ms. This is quite fast! Chrome's fastest possible interval is about 10ms. All other browsers “sample” at about 20-30ms.

  • Alexander von Zuev

    Because there is given property “opacity: 0.4″, but IE(6.*, …, IE8) understand property “filter:alpha(opacity=40)”.

  • http://twitter.com/shipman jon shipman

    it could also be set to fixed or relative. Saying 'must not be static' is a lot shorter than 'must be set to absolute, relative, or fixed'.

  • http://spencercreasey.com Spencer

    Can't seem to get .animate({ borderWidth: 0 }, 1000) to work correctly (from border-width: 10px)

  • http://twitter.com/spencercreasey Spencer Creasey

    OK I guess I can:

    .animate({
      'borderLeftWidth': 0,
      'borderTopWidth': 0,
      'borderBottomWidth': 0,
      'borderRightWidth': 0
    }, 1000);

    But that's pretty annoying…

  • Jordan

    I've noticed that you can also move objects by setting passing in new top and left margin values

  • Tloram

    Wow that seems like a bit of an oversight to me!

    I have dropped this value down to 50ms in my current project (by altering the hardcoded value in jQuery source); no noticeable impact on smoothness of the animation but the CPU usage has dropped massively!

    This REALLY need to be made a parameter to the animate method!

  • Mike

    Tloram, can you tell me the name of the value in jQuery. I, too, would be very interested in having control of this. Thanks!

  • Tloram

    Sure, if you download the development version of the latest jQuery library (at time of posting 1.4.2 it is on line 5769.

    The string you are looking for is:

    “timerId = setInterval(jQuery.fx.tick, 13);”

    Just alter the value 13 to whatever milliseconds you prefer. I have found that at value of between 40-50 works very well as reduces CPU hit considerably when animating.

    If you are using slower, more subtle animation effects I am sure that this value could even be raised to somewhere in the 100ms region… which is why it so badly needs to be made a parameter to the animate method… not all animations have the same requirements!

    T

  • Moghammed

    In the minimized version it’s on line 141, and the “line” is

    W=setInterval(c.fx.tick,13)

  • Anish

    can this be solved by setting the DURATION option in .animate() to 50ms or something?

  • Tloram

    No, duration has nothing to do with the internal jQuery update/render interval.

  • Anish

    to alter the setInterval i need to put the jQuery source in my server know?
    if I'm using the code from another server(google CDN etc.) how can i solve this issue?

  • BlackScorp

    if you wish to setup your own step delay in animation, you can do it with following function:
    var stepTimer = Date.now()+100//Actuall timestamp + step Duration
    $('.foobar').animate({'top':'+=10','left':'+=10' },{
    duration:'slow',
    step:function(){
    if(stepTime < Date.now()){
    // Do something
    stepTime = Date.now()+100; //reset timer
    }
    },
    complete:function(){
    alert('animation done');
    }
    });

    on this way you can setup your own amount of steps

  • http://twitter.com/jwpalmer John Palmer

    Did you try just .animate({ border: 0}, 1000) ?

  • http://blog.spencercreasey.com Spencer

    This is what is expected to work, right? But it doesn't. However, it seems that borderWidth does work now.

    Try in your js console:
    $('.dsq-comment-header').css({border:'10px solid red'}).animate({borderWidth:0}, 1000)
    or
    $('.dsq-comment-header').css({border:'0px solid red'}).animate({borderWidth:10}, 1000)

    These seem to work. Perhaps I missed this.

  • Geeo

    try padding: “5px 5px 0px 0px” in CSS it's not an option, you have to set a unit even if the value is 0 :)

  • kazim44

    can’t we change background-image with animate function?

  • http://twitter.com/AnrietteC Anriëtte Combrink

    If you include jQuery-UI, then you would be able to animate the background-colour, I just did it and it works.

    http://devsnippets.com/article/fading-backgroun…

  • Mike

    you can animate basically any CSS property, ie: size, opacity, border, padding, etc. etc. etc.

  • Brian-

    FWIW, I've always based my animations on the whole 24fps format that used to be used by traditional 2D animators (like Disney and stuff). (24 fps happens to be about the lowest rate that most human are unable to discern.) So, 1000ms/24fps = approx 42 (41.666…) as the interval – which coincides nicely with the '40-50' range you found that seems to work nicely. Most broadcast TV (at least in USA) runs at about 30fps (actually, it's 29.97), so a 33ms interval would work nicely as well I would imagine, though I've found 42 to be good enough for me.

  • Tara_irvine

    is it possible to have $('#divID').animate({“left”: “+=780px”}); but I don't want the animation…

    Really stuck :(

  • Jan

    If you want no animation: you probably just want to do

    var position=$(“#divID”).position();
    $(“#divID”).css({ left: position.left + 780 });

  • Tara_irvine

    worked $('#captions').animate({“left”: “-=780px”}, 1);
    changed the speed :D
    thanks
    I have another question can i reset this animate when it gets to the end of the slideshow?

  • LRegla

    I am pulling my copy of the core library from a CDN (Google loader) and cannot change the minified code without hosting it myself. Has anyone found a workaround for inserting W=setInterval(c.fx.tick,13) outside the library, essentially finding the scope of W and overriding it?

  • http://www.designkanya.com Design Kanya

    I noticed that setting this value to between 40-50 presents the animation a bit jerky, whereas when I set it to 1 (one) to experiment, not only the animation smoothness, but also the response was amazingly good. Of course at the cost of heavy CPU utilization.

  • http://hkansal.myopenid.com/ HKansal

    You'll need to save the original “left” value first. At the end of slideshow, reset the value.

  • mrKalafior

    I have some image as a block element and i want to resize it, when i use animate jquery automatically set display to inline, someone know why?

  • neilk mij

    how can i click a div object about a corner? like in this

    $(“#right”).click(function(){
    $(“.block”).animate({“left”: “+=50px”}, “slow”);
    });

    $(“#left”).click(function(){
    $(“.block”).animate({“left”: “-=50px”}, “slow”);

    but around a square.

  • http://twitter.com/mfolnovich Matija Folnovic

    Hello!
    is it possible to animate eg. -moz-transform: rotate(90deg) ?
    I tried something like:
    $('div').animate({ '-moz-transform': 'rotate(90deg)', '-webkit-transform': 'rotate(90deg)', '-o-transform': 'rotate(90deg)' }), but it didn't work. :( $('div').css( … ) works.

  • Nonameplum

    Is it possible to change the size of div or etc but in direction top-right corner to bottom-left corner ?

  • Yrael

    $(“#square”).click(function() {
    $(“.block”).animate({“left”: “+=50px”}, “slow”);
    $(“.block”).animate({“top”: “+=50px”}, “slow”);
    $(“.block”).animate({“left”: “+=50px”}, “slow”);
    $(“.block”).animate({“top”: “+=50px”}, “slow”);
    });

    Would animate in a square.

  • Yrael

    $(“#square”).click(function() {
    $(“.block”).animate({“left”: “+=50px”}, “slow”);
    $(“.block”).animate({“top”: “+=50px”}, “slow”);
    $(“.block”).animate({“left”: “+=50px”}, “slow”);
    $(“.block”).animate({“top”: “+=50px”}, “slow”);
    });

    Would animate in a square.

  • http://www.learningjquery.com/ Karl Swedberg

    Yes. In your CSS, make the element position: relative or position: absolute; and then set its top property and its right property. The key here is the right property; set it instead of the left property. So, if you want the element to stay within the flow of the document without any offset adjustments, you would do something like this in your stylesheet:

    #myelement {
    position: relative;
    top: 0;
    right: 0;
    }

  • Ricardus

    is there any way of having a preset style?

    .animate({width:’100px’}, 1000)

    into

    $myStyle = “width:’100px’”;
    .animate({$myStyle}, 1000)

  • Ricardus

    managed to work it out!

    option = {};
    option.width = ’100px’;

    .animate(option, 1000)

  • jQueryReady

    I found it! $('.selector').is(':animated')

  • jQueryReady

    Is there any method (or any way) to know if the animation is still running?

  • Jeffdaze

    you can use:

    $('#yourdiv').animate({
    “backgroundPosition”: “-=10px 0px”
    }, 100);

    for example

  • Steren

    Does .animate() use CSS3 transition and transform when possible? or does it always change style values?

  • http://www.learningjquery.com/ Karl Swedberg

    It always changes style values.

  • http://twitter.com/andredal André D. Molin

    Its background-image, not background-position.

  • Thompsongl

    Is it possible to stop the block from moving left once it reaches the end of the div?

    In other words, can you inhibit the .animate function once it reaches a certain point in order to prevent the object from moving an infinite number of times?

  • John

    Sure, stick something like:

    if( $(“.block”).css( ‘left’ ) > 0 )

    before the animate call.

  • http://twitter.com/Jon47 Jonz

    I have noticed that doing animations on windows in IE7 and 8 -thats right, not IE6- and on mac in Firefox on top of background images (such as on this page: http://thecreatorsdocumentary.com/artists) creates some pretty choppy animations.

    If I remove the background image (recommended method is to use this bookmark: http://erkie.github.com/ and point at the top left of the page before blasting) the animation is smooth as butter.

    Just a suggestion, try to avoid doing animations overlaying background images or be prepared for loss of smoothness.

  • Madantk

    hi Auto scrolling function available in Jquery?

  • Anonymous

    Does anyone know if you can add variables as the value of the css attribute? I've tried some ways that I've seen with other JQuery functions, but the animate seems to be more sensitive to it.

    if(j > 0){

    j = j * 600;

    $(“.wrapper”).animate((“marginLeft”: “-=” + j + “px”), 1250);

    }

    …doesn't work.

    Thanks

  • MatTheCat

    $('html,body').animate({scrollTop: $('id').offset().top}, 500);

  • Codekiller66

    You might also like the jQuery.scrollTo Plugin by Ariel Flesler. Pretty cool. :) http://flesler.blogspot.com/2007/10/jqueryscrollto.html

  • wessinit

    can you pause an .animate() call

  • Gooburt

    I might be wrong, but I think marginLeft should not be in quotes.

  • Mereorteg

    I ned that menu works with mouse clic on

  • ShortSchoolBus

    $('#obj').animate({'background-position': '20% 80%'},1000);
    Only the left position animates using this method. It jumps directly to the top position then animates to the left position.

  • http://twitter.com/prabhakarcsengg Prabhakar

    u can try by using .stop()

  • Kathir

    hi master
    i got it…..thanking you

  • Kathir

    i want know about jquery
    please help me

  • Codekiller66

    If you use lowerCamelCase, as in marginLeft then you can leave quotes out, but if you use dashes as in “margin-left”, then you gotta use 'em. It's a matter of personal preference, but I use quotes either way, just to be a prude. :P Remember though, whatever naming convention you choose, values must always be quoted. :)

  • TypeNameHere_____

    This *was* a week ago, so you probably have searched for help else ware, but I have to say that you MUST learn at least some html and css before even touching jQuery… do you?

  • Montoyland

    I'm using an .each() attached to a selector but the animation is only applied to the first match, is there a way to simultaneously animate several matched elements?

  • TypeNameHere_____
  • http://twitter.com/semperos Daniel Gregoire

    I'm animating a background color, but a background color defined in a stylesheet isn't allowing the animation to animate the background. What's the best way to get around this? I want the element to have a default background before the animation is applied.

  • http://www.learningjquery.com/ Karl Swedberg

    For color animations, you'll need to use a color plugin or jQuery UI.

  • DJDarkViper

    I cannot seem to get my “left” attribute to animate. All other attributes animate but “left” just doesn't move anywhere.

    $('#weap-main').animate({“left”: “+=150″}, “slow”, function() {

    and so on and so fourth. But when i do this, its just stationary.

    Inside the weap-main DIV, there are more DIVs that have a “float:left” in them, but it doesnt seem to matter because when normal text is in the weap-main DIV it still doesnt go anywhere…

    i know its playing the animation, opacity works, and the callbacks trigger correctly… but…

  • http://www.learningjquery.com/ Karl Swedberg

    Have you tried making sure that the element's position style property is set to relative or absoute?

  • Jknopp

    var myStyle = {};
    myStyle['width'] = ’100px’;
    .animate(myStyle, 1000);

    This approach allows using vars in place of ‘width’ and ’100px’ also.

  • Tom

    How would you go about doing this?

    $(“.scrollright”).click(function() {

    var thumbHeight = $(“.smallimage”).height();

    $(“.smallimage ul”).animate({ marginTop: '-=thumbHeight' }, “slow”);

    });
    It doesn't seem to work, how would I do it? it worked if I used $(“.smallimage ul”).animate({ marginTop: '-=288' }, “slow”); but I would like for it to detect it

  • http://twitter.com/CubedEye Steven Robinson

    $(“.smallimage ul”).animate({ marginTop: '-='+thumbHeight}, “slow”);

  • http://ucmsdev.co.za Eugene Koekemoer

    Tom, I have a simple slider tutorial for you that uses the animate and margins to animate an object/list of objects. http://ucmsdev.co.za/page/124/Simple%20JQUERY%20Slider
    To use it as a click function, simply remove the $(document).ready call and add a onClick=”sliderBox();” to the element to be clicked.

    ie.

    Animate thumbs

  • http://ucmsdev.co.za Eugene Koekemoer

    It seems you can't post html tags here lol

    That is: < span onClick=”sliderBox();”>Animate thumbs< /span>

    Also, I think you have a problem with your CSS, which is making your code fail. You should probably specify a margin tag for the item you would like to animate.

  • http://ucmsdev.co.za Eugene Koekemoer

    See my post above…..

  • http://ucmsdev.co.za Eugene Koekemoer

    Daniel, do you have a sample code maybe?

    I presume you want the background to simply change color?

    If so, don't use .animate, simply change the css with onClick=”$('#itemToChange').css('background', '#FC3434')”

    else, if you would like to animate a background image, rather create 2 divs and float them over each other. This will allow you to create a simple animated slider for the bottom div. Tricky, yet possible.

  • http://ucmsdev.co.za Eugene Koekemoer

    Montoyland, I'm guessing your elements have ids? Sometimes replacing ids with classes instead, makes one hell-o-va difference.

    The reason for this is that, javascript attaches to the 1st ID element.

    Also, depending on what you would like to achieve, you can eliminate the need for the .each function, as this function requires quite some skill to apply.

    Do you have a sample code maybe?

  • http://ucmsdev.co.za Eugene Koekemoer

    wessinit, pausing is not really an option, though I did see a plugin once…. wait, let me have a look….. ah! here we go:

    http://plugins.jquery.com/project/Pause-Resume-animation

  • http://ucmsdev.co.za Eugene Koekemoer

    Thompsongl, you would love my tutorial. :D

    http://ucmsdev.co.za/page/124/Simple%20JQUERY%20Slider

  • Zipzapduo

    It seems that the code animate doesnt work on a form tag in firefox,why?

  • http://phpdaily.wordpress.com shashi kanth

    Hi, I used animate function like: $(“.block”).animate({“bottom”: “0″, “left”: “+=0px”}, “slow”); It is sliding slow… but can i still reduce the speed of sliding, as i am not able to realize the sliding effect in Chrome, due to my fast internet speed.

  • http://phpdaily.wordpress.com shashi kanth

    Hi, I used animate function like: $(“.block”).animate({“bottom”: “0″, “left”: “+=0px”}, “slow”); It is sliding slow… but can i still reduce the speed of sliding, as i am not able to realize the sliding effect in Chrome, due to my fast internet speed.

  • BiffBaffBoff

    Hey guys,

    Im having trouble with a callback function when using the animate feature. Basically I want it to remove a class after it has finished the animation on an anchor tag. Here is the code:

    blob.animate({
    width : currentPageItem.outerWidth(),
    left : currentPageItem.position().left
    },
    {
    duration : options.speed,
    easing : options.easing,
    queue : false
    },
    function() {
    $('a', this).removeClass('selected');
    });
    As you can see its a plugin, if you need more info let me know, for now you can visit the page here:

    http://www.biffbaffboff.co.uk/test/UIEngine/index.php

    The class im trying to remove is in the nav bar but it doesnt remove, your help will be appreciated!

  • Sachin Tmimt

    sffsfsdf

  • http://www.learningjquery.com/ Karl Swedberg

    Please direct this question to http://forum.jquery.com/

    Thanks!

  • Carlos

    Hi all,

    I'm trying to animate the width of a div but I would like it to grow to the left instead of to the right. The problem is that the axis is located upper-left and I'd like to somehow have it upper-right.

    The only way I've found to do the trick is by moving the div to the left at the same time as I modify the width. The problem is that in computers with low specs/iphone the movement easing is a bit quicker than the width growth, so you can see a white gap on the right whilst the easing takes place.

    I hope I've been clear and this makes sense to you :-)

    Thanks!

  • Carlos

    Sorry, forgot to say that I've tried the solution above

    #myelement {
    position: relative;
    top: 0;
    right: 0;
    }

    but no joy…

  • Carlos

    And I found the solution (I think it's one of Murphy's laws, the faster you ask, the faster you get the solution yourself)

    It was a matter of setting the float property to right as well :-)

    Hope this helps to someone!

  • matteo

    hi!
    i tried an example of the function animate.
    on the test server it works.
    on the production server with https it doesn't work.
    do you know why?

  • Qlidnaque

    this is great

  • Qlidnaque

    this is great!

  • http://twitter.com/nickspacek Nick Spacek

    If you are animating an element, it is important to remember that jQuery sets the style.overflow = 'hidden'. This can cause clipping if you have any child elements that are absolutely positioned outside of the target element.

  • AM

    I am trying to work on tables with some of the row populated and some of them blank where i can edit. Is there a way I can make those changes to database also when user makes any changes to the blank field.

    Your help will be highly appreciated.

  • http://www.logo-design-store.com DesignPlus

    thats really awesome, with jquery everything is possible.

  • Brian

    this is annoying to me

  • Test

    No..not everything possible using jquery.. can you give birth using jquery lol?

  • Adrianjacob

    Hi,

    Im trying to create a custom horizontal accordion style showcase. In terms of actual functionality, i have the framework (which can be seen here):

    http://www.jsfiddle.net/adrian…/

    However my main bug bear (and the clients) is that if you look at the right hand side of the last li, there is always slight movement/flickering as the widths animate up and down.

    Ideally I want it to appear smooth with no dodgy movement on the last item as other things resize. Any idea how I can achieve this?

    A.

  • Timbhowe

    Looked at you code if you are just trying to get ride of the flicker at the far right of the last li then it looks like there is a slight error in your css @ #promo width is 404x should probably be 400px.

    Also you might want to check think about using easing if you need to clean it up more. here is a helpful cheat sheet http://commadot.com/jquery/eas…

  • Broox9

    is it possible to animate the opacity with a “from” and “to” setting as such:

    $(thing).animate({opacity: {“from” : 1, “to”: 0.3}}, 500);

  • http://twitter.com/eliekhoury Elie Khoury

    Broox9, you can do this:

    $(this).css('opacity', 1).animate({'opacity': 0.3}, 500);

  • Wyl_616

    Think you very much

  • sidonath

    The first example is incorrect, it shows that animate() can be used to animate “borderWidth” property, whereas only “borderLeftWidth” and others can be specified (as illustrated in example #60)

    http://bugs.jquery.com/ticket/…

  • Qasimraza1979

    I have a question related to
    Example: Shows a div animate with a relative move. Click several times on the buttons to see the relative animations queued up.

    Is this possible to stop moving the div after certain limit
    For example if i want to move the div elements move between 500 px size area

    like we have here on the bottom of this page a book show case that books can be selected by clicking on left or right buttons
    here is the link
    https://www.packtpub.com/suppo…

    and after certain limits when books are finished then it do not do any thing if you are at extreme right or at extreme left.

    Please any one could provide some suggetion or example related to this

    thanks

  • Alok

    Ho can I get the Code for examples in http://commadot.com/jquery/eas…

  • Tony S

    When I use this on my page, and I go to a link, when I click back on the browser, is there a way to refresh the jQuery, so it will start the animation again?

  • Guest

    What happens when you trigger an animation for a property while anouther animation, animating the same property is still in effect?

  • Guest

    What happens when you trigger an animation for a property while anouther animation, animating the same property is still in effect?

  • Simonauftour

    Is it possible to have a constant speed? Instead animation be done in xy seconds, it takes steps like 2 seconds for every 100px?

  • Mbu725

    Yes. Set the easing function to “linear”. Then specify the proper duration depending on the amount of pixels.

  • Mbu725

    Yes. Set the easing function to “linear”. Then specify the proper duration depending on the amount of pixels.

  • Noob Saibot

    There is no need to use/create a plugin for such simple case

  • Dork89

    Is it possible to pause an animation?

  • Timbhowe

    View the page source.

  • Felipe Correia

    You can use the fadeTo(). http://api.jquery.com/fadeTo/

  • Man

    great tutorial…

  • http://johan.notitia.nl/ Johan

    I think Simonauftour is meaning that the speed (time per pixel) is fixed instead of the total duration.

    I've got the same problem since I want several elements with different heigts have the same animation speed. So a 10px div should open as fast as the first 10px of a 100px div, instead of a very slow 10px and a very fast 100px (since the duration is the same).

  • Mauloa 23

    I have a handful of image thumbnails that will open to separate pages when clicked.
    My question is on the hover/animate state. When I roll over 1 image, I want the remaining images to fade to 50% black. I don't care if the image fades into an existing bg color or if an overlying div goes from 0 to 50% opacity.
    I just need some direction on how to pull this off. Any tips are appreciated!

  • http://techn.ocr.at/ Will K

    Is there a way to add a callback based on the % complete? And if so, is there a way for the “%” it to not match the animated easing?

    As an example, I want to move a box from the left to the right, and I want either callbacks (or custom triggers) at 25%, 50% and 75% based on the distance.

    I could always poll it, but a callback would be much cleaner.

  • Cole

    you can the jquery hover method to animate all images except the one being hovered

  • Andi

    Is there a way to expand the menu to the left side?
    My menu is on the right side of the homepage and submenu should slide to the left side.
    Please help!!

  • Scott Pilgrim

    how about a setTimeout based on animation duration?

  • Libin4646

    very nice. i sure i can make a wonderful application using this info.

  • Jaseinatl

    How can you tell if an element is animating? And can you tell the final state of the animation?
    If I set a button to fade an image on click and it has a long duration, if the user clicks the button again, would it reset the duration and apply the new animation? Or would it queue the new animation? And what happens if you animate an element to it's current state (no change)?

  • Bob

    how do you delay the beginning of the mouseover/mouseout….i have a lot of animated pop ups/tool tips and i want about a quarter second delay so that the animations don't begin immediately….that way, whipping your mouse over the buttons don't start the animation, but stopping and hovering will…..also, i would like the delay the mouseout so that the tool tips don't immediately disappear if the user 'accidentally' rolls out for a fraction of a second….

  • Bob

    btw, this is what i'm using:

    $(this).find(“span”).animate({opacity: 0, top: “-320″}, {queue:false, duration:250, complete: function(){
    $(this).attr({“style”: 'display:none'});