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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Time for action – animating the post links<br />

[ 227 ]<br />

Chapter 8<br />

We're now ready to begin scrolling the post links within the marquee. We can do this using<br />

our custom event.<br />

1. After the getJSON() method, add the following code to the page:<br />

$("body").delegate("#marquee", "marquee-ready", function() {<br />

var marquee = $(this),<br />

postLink = marquee.find("a").eq(0);<br />

width = postLink.width() +<br />

parseInt(postLink.css("marginRight")),<br />

time = 15 * width;<br />

postLink.animate({<br />

marginLeft: "-=" + width<br />

}, time, "linear", function() {<br />

$(this).css({<br />

marginLeft: 0<br />

}).appendTo(marquee.find("div").eq(0));<br />

marquee.trigger("marquee-ready");<br />

});<br />

});<br />

2. Our example is now complete. When we run the page at this point, the posts should<br />

begin scrolling from left to right.<br />

What just happened?<br />

We use the <strong>jQuery</strong> delegate() method to bind an event handler to our custom<br />

marquee-ready event. We need to use event delegation to achieve this because when<br />

this part <strong>of</strong> the code is executed, the JSON response is unlikely to have returned so the<br />

marquee element won't even exist. Attaching the event handler to the body <strong>of</strong> the page<br />

is an easy way to prepare the page for when the marquee element does exist.<br />

Within the anonymous event-handling function, we first cache a reference to the marquee<br />

element using the this object, which is scoped to our marquee element. We then select<br />

the first link in the marquee, and determine its total width including margin.<br />

We also work out what is effectively the speed <strong>of</strong> the animation. <strong>jQuery</strong> animations use a<br />

duration to determine how quickly an animation should run, but the problem this causes<br />

us is that posts with longer titles will move faster, because they have a greater distance to<br />

animate in the same amount <strong>of</strong> time.

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

Saved successfully!

Ooh no, something went wrong!