02.06.2013 Views

jQuery 1.4 Animation Techniques - Index of

jQuery 1.4 Animation Techniques - Index of

jQuery 1.4 Animation Techniques - Index of

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

$(document).keydown(function(e) {<br />

if (e.which === 39) {<br />

bg.animate({ "backgroundPosition": "-=1px" }, 0, "linear");<br />

mg.animate({ "backgroundPosition": "-=10px" }, 0, "linear" );<br />

fg.animate({ "backgroundPosition": "-=20px" }, 0, "linear" );<br />

}<br />

});<br />

[ 189 ]<br />

Chapter 7<br />

If we run this page in a browser now, we should find that as we hold down the right arrow<br />

key, the different background slices move at progressively slower speeds with the foreground<br />

almost rushing past, and the background moving along leisurely.<br />

What just happened?<br />

In the script we first cache the selectors we'll be using so that we don't have to create a new<br />

<strong>jQuery</strong> object and select the elements from the DOM each time the background-position<br />

changes, which will be very frequently indeed. We then set a keydown event listener on the<br />

document object. Within the anonymous function we use as the event handler, we check<br />

whether the key code supplied by the which property <strong>of</strong> the event object (this is normalized<br />

by <strong>jQuery</strong> so it will be accessible cross-browser) is equal to 39, which is the key code returned<br />

by the right arrow key.<br />

We then call the animate() method, which is extended by the cssHooks bgpos.js file<br />

to allow us to specify backgroundPosition as the style property to animate. We supply<br />

relative values <strong>of</strong> +=1px, +=10px, and +=20px to move each layer at progressively faster<br />

speeds which gives us the parallax effect. These animations are called simultaneously<br />

and also have very short durations and linear easing. This is the last thing our keydown<br />

handler needs to do.<br />

Pop quiz – implementing the parallax effect<br />

1. Why is it necessary to use linear easing in the previous example?<br />

a. To prevent a flickering effect<br />

b. It's not necessary, we just used it for fun<br />

c. To prevent the animation using the default easing type <strong>of</strong> swing, which<br />

causes a slowing down at the start and end as this would stop the animation<br />

from running smoothly<br />

d. To slow the animation down slightly

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!