animate() creates custom animations by changing numeric CSS properties over time. It can animate properties such as left, top, width, height, and opacity.
The element must be positioned in a way that allows left or top to affect it, for example with position: relative.
$("#b1").on("click", function () {
$("#d1").animate({ left: "+=10px" });
});
Demo: move an image with animate() →
$(selector).animate({ properties }, duration, easing, complete);
"slow", "fast", or milliseconds."swing" and "linear".position() returns the current coordinates relative to the element's offset parent.
const position = $("#d1").position();
You can display the left coordinate in another element:
$("#d2").text(position.left);
Demo: animate and display the current position →
The original tutorial repeats movement by passing the same function as the animation completion callback:
function startMove() {
$("#d1").animate({ left: "+=10px" }, "fast", startMove);
}
When the movement reaches a chosen limit, you can reset the element. The original example uses offset():
$("#d1").offset({ left: 100 });
offset() works with document coordinates, while position() reports coordinates relative to the offset parent, so keep that distinction in mind when combining the two.
Demo: repeat animation with a callback →
Core animate() focuses on numeric CSS values. For the color examples in this tutorial collection, continue to color animation with jQuery UI.
← Previous: slideToggle() · jQuery Effects · Next: color animation →
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.