Get in Line...
A few words about how the animate() method handles sequencing. Most readers are probably already familiar with setting up sequential animations. For this, we can use method chaining:
// find the element we need
$("#box")
// specify what we want to animate
.animate({ left:"-=100" })
// the next animation call is added to the execution queue
.animate({ top:"-=100" })To run animations in parallel, you'll need to make the following change:
// find the element we need
$("#box")
// specify what we want to animate
.animate({ left:"+=100" })
// the next animation call will ignore the queue
.animate({ top:"+=100" }, { queue:false })There's also a wonderful function stop() that lets you halt the current animation midway and clear the queue if needed. To provide different behaviors, it accepts three parameters:
queue
queue name;
for working with the animation queue "fx" this parameter is omitted ("fx" is the default queue)
clearQueue
flag to clear the queue
jumpToEnd
apply the animation result, or not
Here's an example that begs for some experimentation:
A note for the future: if you've built a dropdown menu that keeps dropping down and disappearing after you've been playing with the mouse, you need to stick a
stop()in the event handler.
Let's try it out on a live example:
By default, all animation on an object goes into the "fx" queue, but since version 1.7 you can specify a custom queue:
Why would we need a custom queue? For parallelizing animation, of course — so we can start one animation queue and at any other moment start another one. Maybe this was designed with games in mind? But why guess — let's play:
Open the page and run the script — a game character will appear, and the game is on!
The script with the keydown event handler is already running, and you can make Mario run around the page using the arrow keys or the R, D, F, and G keys:
In this example, two queues are used — x and y, corresponding to the coordinate axes along which we move. When the ← key is pressed, the left value decreases by 100px in the x queue. When → is pressed, we clear the x queue and increase left by 100px. For movement along the y axis, we use the queue of the same name and the ↑ and ↓ keys.
From this chapter you should have learned that the
WASDlayout has an alternative :)All rights to Mario belong to Nintendo, so be careful with him.
Last updated