Custom Animation
Animate any numeric CSS property with .animate().
Syntax
$(selector).animate({props}, speed);.animate() tweens numeric CSS properties from their current value to the ones you specify.
$("#box").animate({
left: "200px",
opacity: 0.5,
width: "150px"
}, 600);Only properties with numeric values can be animated (not colors, without a plugin). The element usually needs position set for movement.
Example
Loading editor…
Press Run to see the result.
When to use it
- A progress bar fills from 0% to the user's score width using .animate({ width: score + '%' }).
- A notification badge bounces to the right and back using chained .animate() calls on the left property.
- A sticky header shrinks its padding when the user scrolls by animating padding-top from 20px to 5px.
More examples
Animate element width (progress bar)
.animate() smoothly transitions the width CSS property over 800 ms, simulating a progress bar fill.
<div style="background:#ddd;height:20px;width:300px;">
<div id="bar" style="background:#4caf50;height:20px;width:0%;"></div>
</div>
<button id="run">Fill to 75%</button>
<script>
$(function () {
$("#run").click(function () {
$("#bar").animate({ width: "75%" }, 800);
});
});
</script>Move an element across the page
Animating the left property moves the element horizontally; position:relative is required for this to work.
<div id="ball" style="position:relative;width:40px;height:40px;background:#e74c3c;border-radius:50%;"></div>
<button id="move">Move right</button>
<script>
$(function () {
$("#move").click(function () {
$("#ball").animate({ left: "200px" }, 600);
});
});
</script>Chain animations for bounce effect
Three chained .animate() calls on top create a quick up-then-settle bounce without a plugin.
<div id="badge" style="position:relative;display:inline-block;padding:4px 10px;background:#e74c3c;color:#fff;">3</div>
<button id="bounce">Bounce</button>
<script>
$(function () {
$("#bounce").click(function () {
$("#badge")
.animate({ top: "-10px" }, 150)
.animate({ top: "4px" }, 100)
.animate({ top: "0px" }, 100);
});
});
</script>
Discussion