jQuery Stop
The jQuery stop()
method is used to stop animations or effects before they are completed. This is useful when you want to prevent animations from overlapping or when the user triggers a new action that should interrupt ongoing animations.
Key Topics
Basic Usage of stop()
The stop()
method stops the currently running animation on the selected element.
$("#element").stop();
Explanation: This code stops any ongoing animation on the element with the ID element
. The animation will freeze at its current state.
Using stop()
with Parameters
The stop()
method accepts two optional parameters:
- clearQueue: If set to
true
, it clears the animation queue for the selected element. - jumpToEnd: If set to
true
, it immediately completes the current animation.
$("#element").stop(true, true);
Explanation: This code stops the animation, clears the animation queue, and immediately completes the current animation for the element with the ID element
.
Example: Stopping Animations
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Stop Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="box" style="width: 100px; height: 100px; background-color: lightblue;"></div>
<button id="startButton">Start Animation</button>
<button id="stopButton">Stop Animation</button>
<script>
$(document).ready(function() {
$("#startButton").click(function() {
$("#box").animate({ left: "300px", opacity: 0.5 }, 5000);
});
$("#stopButton").click(function() {
$("#box").stop();
});
});
</script>
</body>
</html>
Explanation: This example demonstrates how to start and stop an animation on a box element. The startButton
triggers an animation that moves the box and changes its opacity, while the stopButton
interrupts it.
Key Takeaways
- Interrupt Animations: Use
stop()
to prevent overlapping animations or interruptions. - Parameter Control: The
clearQueue
andjumpToEnd
parameters provide fine-grained control over animation behavior. - Dynamic Effects: Combine
stop()
with other jQuery methods to create responsive interactions.