jQuery 2.

0 Animation Techniques Beginner's Guide

Adam Culpepper Dan Wellman

Chapter No. 2 "Image Animation"

In this package, you will find:
A Biography of the authors of the book A preview chapter from the book, Chapter NO.2 "Image Animation" A synopsis of the book’s content Information on where to buy this book

About the Authors
Adam Culpepper is a frontend web developer who works for Envoc, a software development firm, located in Baton Rouge, Louisiana. He is very active in his community; organizing, founding, and sitting on the board of many industry-related groups and organizations in his area. When he's not reading, writing, working, organizing, or attending a community event, he's spending time with his great friends and family or his girlfriend Amber, his son Aiden and his cat Emma. Adam can be reached at ) or through Twitter . his website (

For More Information: www.packtpub.com/jquery-2-0-animation-techniques-beginners-guide/book

I dedicate this book to my girlfriend, Amber, who tolerates my time spent reading, writing, and learning. To my son Aiden and my cat Emma, who both frequently break my concentration while writing. To my mom, who has always encouraged me to reach for my dreams (except for my childhood dream of growing up to be a puppy). To the best damn boss in the world, Calvin Fabre. Also, I'd like to give special thanks to the period, comma, and the semicolon. Without you guys, I would have gotten a lot more restful nights.

Dan Wellman is an author and web developer based on the South coast of the UK. By day he works alongside some of the most talented people he has had the pleasure of calling colleagues, for a small, yet accomplished digital agency called Design Haus. By night he writes books and tutorials on a range of frontend topics. He is hopelessly addicted to jQuery. His life is enriched by four wonderful children, a beautiful wife, and a close circle of family and friends. This is his fifth book. I would like to thank the hugely supportive and patient editorial team at Packt, without whom this book would not exist. I would also like to thank the reviewers, especially Ben Nadel and Cyril Pierron, who put aside their own personal projects and dedicated countless hours to ensuring the book's technical accuracy. I'd also like to say a big Hey! to some of my closest friends, in no particular order; Andrew Herman, Steev Bishop, Aaron Matheson, Eamon O'Donoghue, James Zabiela, Mike Woodford, and John Adams.

For More Information: www.packtpub.com/jquery-2-0-animation-techniques-beginners-guide/book

jQuery 2.0 Animation Techniques Beginner's Guide
jQuery is a cross-browser JavaScript library designed to simplify the client-side scripting of HTML, and is the most popular JavaScript library in use today. Using the features offered by jQuery, developers are able to create dynamic web pages. This book will act as a resource for you to create animation and advanced special effects in your web applications, by following the easy-to-understand steps mentioned in it. jQuery 2.0 Animation Techniques Beginner's Guide will allow you to master animation in jQuery to produce slick and attractive interfaces that respond to your visitors' interactions. You will learn everything you need to know about creating engaging and effective web page animations using jQuery. The book uses many examples and explains how to create animations using an easy, step-by-step, beginner's guide approach. This book provides various examples that gradually build up the reader's knowledge and practical experience in using the jQuery API to create stunning animations. The book starts off by explaining how animations make your user interface interactive and attractive. It explains the various methods used to make the element being animated appear or disappear. It provides a set of steps to create simple animations and show fading animations. You can later learn how to make complex animations by chaining different effects together as well as how to halt a currently running animation. You will find out how to slide your animation elements and learn to create custom animations that can be complex and specialized. You will learn how to obtain and set up jQuery UI—the official user interface library for jQuery. This book will tell you how to animate a page's background image, and will teach you how to make images scroll in a certain direction and at a certain speed depending on the movement of the mouse pointer.

What This Book Covers
Chapter 1, Getting Started, covers the basics including downloading jQuery and setting up a development area, a brief history of animation on the Web, when and where not to use animation, how animation can enhance an interface, and the animation methods exposed by jQuery. A basic example of animation is also covered. Chapter 2, Image Animation, uses a simple approach to creating an image slider. We then build features into the slider and are le with a script worthy of your next development project.

For More Information: www.packtpub.com/jquery-2-0-animation-techniques-beginners-guide/book

Chapter 3, Background Animation, takes us through the journey of creating animated background images and background color when our user scrolls down our site. This very subtle animation adds a lot of aesthetic appeal to websites. Chapter 4, Navigation Animation, covers creative ways to add animation to navigation on our websites. We'll be fading the background color of our web page and smooth scrolling to clicked links on the page. Chapter 5, Form and Input Animation, focuses on animation that is triggered by our user's interaction with the form. We will guide our users through our form using animations for form validation and to give our form a better experience overall. Chapter 6, Extending Animations with jQuery UI, looks at the additional effects added by jQuery UI, the official UI library built on top of jQuery. We look at each of the 14 effects as well as covering the easing functions built into the library. Chapter 7, Custom Animation, focuses on the method, which jQuery provides for us as a means of creating custom animations not already predefined. This extremely powerful method allows us to animate almost any CSS-style property to easily create complex and attractive animations. Chapter 8, Other Popular Animations, looks at some common types of animations found on the web including proximity animations triggered by the mouse pointer, animated headers, and a modern-day equivalent to the marquee element. Chapter 9, CSS3 Animations, covers how we can use CSS3 to create attractive animations driven by the latest CSS transforms and how jQuery can be used to make the process easier. Chapter 10, Canvas Animations, looks at the HTML5 canvas element and shows how it can be used to create stunning animations without the use of Flash or other proprietary technologies. The book closes with an in-depth example teaching how to create an interactive game using nothing but HTML and JavaScript.

For More Information: www.packtpub.com/jquery-2-0-animation-techniques-beginners-guide/book

Image Animation
In this chapter we'll be creating a basic image rotator (slider) using jQuery animation functions. We'll also be extending the functionality of our script to pause the animation when our users hover over the rotator. Then we'll be adding previous and next links to the script to allow users the ability to scroll through our images at their own pace. Lastly, we'll be adding in a pagination link, so that our user can page through the images in our image rotator.

2

Image animation
On your journey through the world of jQuery, you'll find that some form of content or image rota on is necessary at mes. Image rotators are a more visually appealing way to display sets of images than having them displayed straight down the page. They can also lead to a more compact and efficient design, allow for preloading of content or images, and also can give us the ability to control what and when the user sees.
Image rotators are o en referred to as a slideshow, slider, scroller, or carousel, based on the varying func onality.

We'll be talking about the following anima on methods in this chapter:
  

fadeIn() fadeOut() fadeToggle()

For More Information: www.packtpub.com/jquery-2-0-animation-techniques-beginners-guide/book

Image Anima on

Fading animations
The fadeIn() and fadeOut() methods perform the least complex anima ons available via jQuery. They simply adjust the opacity of selected elements to either show or hide the element and can be used with no addi onal configura on. The fadeToggle() method is almost as simple, but does provide some basic logic to check the selected element's current state. Elements that are hidden with display:none will be set to their correct display type (either display:block for block-level elements or display:inline for inline elements) where possible at the start of a fadeIn() anima on. It is important to note this as your CSS styles might impact the appearance of an element that you are fading in. An element's natural display type is used wherever possible, so hidden <li> elements are set to display:listitem, and hidden <td> elements are set to display:table-cell. Elements that are set to display:block (or are set to another display type but nevertheless visible on the page) will be set to display:none at the end of a fadeOut() anima on. Elements will switch between their visible and non-visible states when the fadeToggle() method is used. Elements that are to be shown using the fadeIn() method must be ini ally hidden with display:none while the elements that are hidden with visibility:hidden for example, will remain hidden at the end of the anima on because the fade methods specifically alter the opacity and display property, and not the visibility property. In their simplest forms, these methods can be used without any addi onal configura on. We can simply call the methods on any collec on of selected elements without using any arguments:
  

$(elements).fadeIn(); $(elements).fadeOut(); $(elements).fadeToggle();

When no arguments are provided, the anima ons will have the default dura on of 400 milliseconds and the default easing of swing. We'll talk about anima on easing very shortly.

Configuring the animations with arguments
With arguments, the fading methods may take the following form (square brackets denote op onal arguments):
$(elements).fadeIn([duration] [,easing] [,callback]); $(elements).fadeOut([duration] [,easing] [,callback]); $(elements).fadeToggle([duration] [,easing] [,callback]); [ 22 ]

For More Information: www.packtpub.com/jquery-2-0-animation-techniques-beginners-guide/book

Chapter 2

We can control the dura on of the anima on using the duration argument to specify either an integer in milliseconds or strings "slow", and "fast". These strings are shortcuts for 600 and 200 milliseconds respec vely. The default dura on given if one isn't specified is 400. We can also supply 0 as the duration argument, which will effec vely disable the anima on. It's unlikely that we'd need to do this as it would be more efficient to not use an anima on at all, but it is useful to know. I should point out that the fade will s ll occur; it will just happen over a dura on of 0 milliseconds. Doing this would be the same as using .hide(), essen ally. The easing argument can be changed from its default value of swing to linear, which causes the anima on to progress at the same speed throughout the anima on. The default, swing, causes the anima on to start slowly, speed up slightly, and then slow down towards the end of the anima on.
The duration argument relates to the length of me the anima on takes to run and not the speed of the anima on. Therefore, a higher value will mean a slower, longer anima on and not a faster, shorter anima on. The number of easing types can be greatly increased using plugins. We'll look at the extra easing types added by jQuery UI later in the book.

We may supply a callback func on (either a func on reference or an anonymous func on, with the la er being more commonplace). This callback func on will be executed a er the anima on ends for each element in the selec on, so it may be triggered more than once if more than a single element is being animated.
A callback func on is a func on that is passed inside another func on as a parameter. The following example of callback code triggers an alert once the anima on is complete (callback in bold):
$(".selector").fadeOut("slow", function() { alert("callback triggered!"); });

You'll o en see the preceding line forma ed like the following block of code for readability:
$(".selector").fadeOut("slow", function() { alert("callback triggered!"); });

[ 23 ]

For More Information: www.packtpub.com/jquery-2-0-animation-techniques-beginners-guide/book

Image Anima on

Time for action – setting up the markup and styling
To begin with, we need to create the elements that will be used in the example and the styling to set their visual appearance.

1.

Create a new HTML document using the template file we created in Chapter 1, Ge ng Started, and in between the <body> tag add the following underlying markup for our image slider:
<div class="container"> <div id="slider"> <img src="http://placekitten.com/200/200?image=1"> <img src="http://placekitten.com/200/200?image=2"> <img src="http://placekitten.com/200/200?image=3"> <img src="http://placekitten.com/200/200?image=4"> <img src="http://placekitten.com/200/200?image=5"> <img src="http://placekitten.com/200/200?image=6"> <img src="http://placekitten.com/200/200?image=7"> </div> </div>

2. 3. 4.

Save the page in the jquery-animation directory as image-rotator.html. We'll also need to add in our stylesheet for this example. In the HTML file we just created, add image-rotator to our placeholder stylesheet link. Next we should create the stylesheet we just linked to. In a new file, add the following code:
.container { position:relative; width:200px; height:200px; } #slider img { position:absolute; display:none; border-radius:3px; }

5.

Save this file as image-rotator.css in the css folder within our project folder.

[ 24 ]

For More Information: www.packtpub.com/jquery-2-0-animation-techniques-beginners-guide/book

Chapter 2

What just happened?
For this example, we'll be using seven images in our image rotator. This can easily be changed based on our needs by simply adding addi onal images to <div id="slider">. We wrapped our #slider element in a <div> element with a class of container so that we can set the dimensions of our image rotator in case all our images aren't of the same width and height. Also, we set position:relative to the #slider div so that the rotator images being set to position:absolute don't get removed from the page flow.
When an element is set to position:absolute, the element no longer holds open the space that it's placed in, which allows other elements behind or in front of it, based on the other CSS used on the surrounding elements. This is similar to what happens when an element is floated and it's removed from the page flow. It's important to note that in some cases if an element (or group of elements) are set to position:absolute without a parent element being set to position:relative, the position:absolute elements could come out of their parent element, which would collapse the parent element.

The images are set to position:absolute because they need to stack behind each other so that our image rotator element doesn't jump around as the images are being faded in and out. This is needed because all of the images will occupy the same rela ve posi on on the page. However, we only want 1 image to display at a me. Using display:none will turn off the visibility on all our images. This is needed so that we don't have to worry about the stacking order of our images. We want a good presenta on on our images so we added a small border-radius on the images to so en the corners.
Stack order refers to the order in which elements are stacked on a page. If an element is loaded before another element, it will be before the following element. The stack order can be modified in CSS using z-index, and by adding position to an element.

Pop quiz – using fadeIn()
Q1. Which strings can be passed into the fadeIn() method as the first argument? 1. The strings "short" or "long", which refer to the dura on of the anima on. 2. The strings "low" or "high", which refer to the opacity that the element is faded to. 3. The strings "slow" or "fast", which refer to the dura on of the anima on. 4. A hexadecimal string specifying background-color of the element
[ 25 ]

For More Information: www.packtpub.com/jquery-2-0-animation-techniques-beginners-guide/book

Image Anima on

Q2. What else can be passed into the method? 1. A string specifying the easing func on to use for the anima on, and a callback func on to be executed once the anima on ends. 2. An object containing addi onal configura on op ons. 3. An array containing addi onal configura on op ons. 4. A callback func on to be executed at the start of an anima on, and a callback func on to be executed at the end of the anima on.

Scripting the image slider
Next, we're going to add the finishing touches to our image rotator by adding the jQuery code that'll animate our images.

Time for action – scripting the image rotator
Now let's add the code for the script that will animate our images. Add the following code inside the anonymous func on below the <body> tag:
var image = $("#slider img"); var numSlides = image.length; var activeSlide = 0; var speed = 2000; var fade = 1000; var timer = setInterval(rotate, speed); image.eq(activeSlide).show(); function rotate() { activeSlide++; if (activeSlide == numSlides) { activeSlide = 0; } image.not(activeSlide).fadeOut(fade); image.eq(activeSlide).fadeIn(fade); }

What just happened?
The first thing we did was we cached a reference to all the <img> elements located inside the #slider element. We'll be referencing it several mes, so it is more efficient to only select it from the Document Object Model (DOM) once. For performance reasons, it is generally best to minimize the number of DOM opera ons that are carried out.
[ 26 ]

For More Information: www.packtpub.com/jquery-2-0-animation-techniques-beginners-guide/book

Chapter 2

For coun ng the number of images we used length(). This counts the number of child elements (<img>) inside the parent element (#slider). For our example, we used seven images. Using the length() func on to count the number of <img> elements, we can easily add or remove images from the image slider without altering the jQuery code. Our activeSlide variable is set to 0 so that we start with the first image in our set. This is generally something you won't want to change unless you want to start on a specific image. This number can be changed to any number you like, as long as we have at least that number of images in our set of images. The activeSlide variable represents the posi on within the group of elements we just selected. The length() func on returns the number of elements, star ng from 0. In our example, image.length() will return 6 and therefore activeSlide can be 0 to 6 since there are seven <img> elements. We ini alize activeSlide to 0, so we start at the first image in the sequence. If we want to start on a different image, ini alize activeSlide to that posi on within the group keeping in mind that the first posi on is 0 and not 1. To set the me between each execu on of the rotate() func on, we set the speed variable to 2000 milliseconds (2 seconds). 2 seconds is a good speed for our example but you'll want to set it to a longer dura on depending on the images that you're rota ng. If you have text on your images that you want your users to read, you should set the rota on speed based on how long you think it will take your users to comfortably read all the text. If you have images with high detail in them, set the speed to something you think is a generous amount of me to take in all the detail. In case you have a clickable element that requires a "call to ac on", this me will need to be taken into considera on based on how long it takes the user to digest the informa on and take the ac on you want them to take. Our fade variable is set to 1000 (1 second) as this is a decent speed for fading out the images. This can be changed to fit your needs and you'll find that there is no standard me for it or the speed. You'll need to tailor these mes to give your users the best possible experience on your website. The setInterval() (na ve JavaScript method) func on creates a mer within the script which executes the func on that's called every interval. In our example, setInterval() will execute the rotate() func on, but wait to call it again un l the amount of me specified in the speed variable has passed. Since speed is set to 2000, the rotate() func on will be executed every 2 seconds.
With arguments, the setInterval event may take the following form: setInterval(function, duration);

[ 27 ]

For More Information: www.packtpub.com/jquery-2-0-animation-techniques-beginners-guide/book

Image Anima on

We then tell the script to display the ac ve image using show(). Since we set the activeSlide variable to 0 ini ally, the first image in our set will be displayed first. This is needed because if you recall, in our CSS we're turning off the visibility of all of the images in our rotator using display:none. If you change the ini al value of the activeSlide variable, then that image will be the first one to be shown when the script starts. Next, we move on to the meat of our script. For our vegetarian readers, whatever protein equivalent you eat in your diet, Soy? Tofu? Anyway, the rotate() func on is where we do most of the heavy li ing in our code. The code above the rotate() func on is mostly the se ngs for our image rotator to use. Inside our beefy rotate() func on we have a variable (activeSlide) that we're incremen ng by one each me it is called. This is needed to set our ac ve image to the next image in our set each me the func on loops. The if statement is used to reset the activeSlide number back to 0 once the script has reached the last <img> element in the selected group. Finally, we have the two most important lines in our code (arguably). We're using the fadeOut() anima on func on for all images that is not() our ac ve image. Then we're using fadeIn() for the image that is equal to the activeSlide image. You'll no ce the variable fade inside our fadeOut() and fadeIn() anima ons. This determines the speed at which the anima on is performed. Along with some other jQuery anima on func ons, "slow" and "fast" can also be used—which is 600 and 200 milliseconds respec vely. This is a screenshot of what we just created using the previous code. You'll no ce how the first image fades out at the same me our next image fades in. This effect is called cross-fading.

[ 28 ]

For More Information: www.packtpub.com/jquery-2-0-animation-techniques-beginners-guide/book

Chapter 2

Pop quiz – length() and milliseconds
Q1. What does length() refer to? 1. The character count of a variable. 2. The number of elements in the object. 3. The width of the object. 4. The amount of me an anima on should run for. Q2. How many milliseconds are there in 1 second? 1. 10 2. 100 3. 1000 4. 10000

Time for action – extending the pause-on-hover functionality
Pause-on-hover is necessary when your images have a lot of detail, text that your users need to read, or have a specific call to ac on that you want them to make. Even if you don't have need of any of those things, it's s ll a good idea to add this func onality as it allows the user to get a good look at the images if they wish. The following screenshot illustrates that the image rota on has stopped when the user hovered over the image:

[ 29 ]

For More Information: www.packtpub.com/jquery-2-0-animation-techniques-beginners-guide/book

Image Anima on

To detect when we hover on and off our image rotator so that we can pause our image rotator, we need to add the following code to the line below image.eq(activeSlide).show();:
$("#slider").hover(function() { clearInterval(timer); }, function() { timer = setInterval(rotate, speed); });

What just happened?
We added a hover event to gain the ability to tell our script when we're hovering over the #slider element and when we've moved away from the element. We're using clearInterval() (na ve JavaScript method) on the timer variable to stop the mer on our rotator, effec vely pausing the anima on.
More about the hover event can be found here: http://api.jquery.com/hover/

It's important to note that stop() and clearQueue() are other methods to stop an anima on or func on from running. However, in this example, we don't want to use them because they stop our anima ons immediately. That can mean it will pause an anima on halfway through and will display both (the current ac ve and the next ac ve) images par ally faded on top of each other. Alterna vely, we could have le the interval running and used a flag in the rotate() func on to determine whether to perform the fadeIn() or fadeOut() methods. The next line tells the script that we are no longer hovering over it and to resume anima ng the images. The mer is then reset back to what we originally set it to at the beginning using setInterval (na ve JavaScript method).

Time for action – extending the previous and next link features
To give your users more controls over the speed of your rota ng images, we're going to add next and previous links as shown in the following steps:

1.

We need to add the anchor tags that will be used for our previous and next links. To do this, add the following code between the last two </div> tags:
<a id="prev">prev</a> <a id="next">next</a>

[ 30 ]

For More Information: www.packtpub.com/jquery-2-0-animation-techniques-beginners-guide/book

Chapter 2

2.

Our next and previous links will need some basic styling, so let's add the following lines of CSS to the bo om of our image-rotator.css file:
#prev, #next { position:absolute; bottom:10px; padding:5px 10px; color:#000; background:#FFF; border-radius:3px; text-decoration:none; opacity:0.7; } #prev:hover, #next:hover { opacity:1; cursor:pointer; } #prev {left:10px;} #next {right:10px;}

3.

For handling the click events on the next and previous links, we'll need to add the following code right above the rotate() func on:
$("#prev").click(function(event) { activeSlide--; rotate(); event.preventDefault(); }); $("#next").click(function(event) { activeSlide++; rotate(); event.preventDefault(); });

4.

Add the following lines of code above image.not(activeSlide).
fadeOut(fade);:
if (activeSlide < 0) { activeSlide = numSlides - 1; }

5.

Update the rotate() func on by replacing activeSlide++ with the following code:
if (!pause == true) { activeSlide++; } [ 31 ]

For More Information: www.packtpub.com/jquery-2-0-animation-techniques-beginners-guide/book

Image Anima on

6.

Find the hover() func on and replace it with the following code (the new code is highlighted):
$("#slider, #prev, #next").hover(function() { clearInterval(timer); pause = true; }, function() { timer = setInterval(rotate, speed); pause = false; });

The following screenshot shows that, a er the next link is clicked, our image rotator moves to the next image:

What just happened?
In the third step, we're adding in two click func ons for the previous and next links. We are decremen ng the ac ve image number by one on the previous func on and incremen ng by one on the next func on. Then we need to call the rotate func on again so that our old image fades out and our new one fades in. We use preventDefault() (na ve JavaScript method) so that the previous and next links don't add a hashtag (#) to the URL in our address bar. This prevents the previous and next links from working like a tradi onal anchor tag. The fourth step allows us to move backwards in our image set. This if statement is similar to the if statement we already have in our rotate() func on used to reset the ac ve variable if it's equal to the number of images in our rotator.
[ 32 ]

For More Information: www.packtpub.com/jquery-2-0-animation-techniques-beginners-guide/book

Chapter 2

We need to change the rotate() func on so it only increments the active image variable if our image rotator isn't being hovered over. To do this, we replaced the line that increments our activeSlide variable with an if statement. Using this if statement we're telling the script to only allow the activeSlide variable to increment if our user is not hovering over the image rotator. We'll need to add in our next and previous links to the pause-on-hover func on so that the image rota on will pause when you hover over those as well. This can be achieved by adding a comma a er #slider, and adding in our #next and #previous ID selectors. We're se ng the pause variable to a Boolean value of true or false based on whether or not we've triggered the hover event. This is needed to tell the rotate func on to only increment the activeSlide variable if we are not hovering over it. To tell our script we are hovering over it, we're se ng the variable pause to a value of true. Then we set it to false once our cursor leaves the image rotator.

Pop quiz – preventDefault() and setInterval()
Q1. What is preventDefault() used for? 1. Preven ng the script from defaul ng variables in the func on. 2. Preven ng the default ac on on an event it's used on. 3. Turning off all JavaScript errors in the func on that it's used in. 4. Turning off JavaScript errors for variables that return a value of null. Q2. What are the two arguments for the setInterval() method that need to be used? 1. speed and time 2. function and duration 3. duration and speed 4. speed and function

Time for action – extending the pagination functionality
To give our users even more control over our image rotator, we're going to add what's called pagina on. Pagina on allows you to move directly to a specific image in our rotator instead of having to click the next and previous links un l we find the image we're looking for. This func on is very helpful if we have a large number of images in our image rotator. To add pagina on we perform the following steps:

[ 33 ]

For More Information: www.packtpub.com/jquery-2-0-animation-techniques-beginners-guide/book

Image Anima on

Let's start by adding the following code to image-rotator.css:
#pagination { position:absolute; top:10px; width:100%; text-align:center; } #pagination a { padding:2px 5px; color:#000; background:#FFF; border-radius:3px; text-decoration:none; opacity:0.7; } #pagination a:hover { opacity:1; cursor:pointer; }

1. 2.

In image-rotator.html, add the following line directly under var pause;:
var paging = "";

In our HTML, we need to add the following code under <a id="next" href="#">next</a>:
<div id="pagination"></div>

3.

Place the following code below image.eq(activeSlide).show();:
for (var page = 0; page < numSlides; page++) { paging += "<a rel=###BOT_TEXT###quot;" + (page + 1) + "###BOT_TEXT###quot;>" + (page + 1) + "</a>\n"; } $("#pagination").html(paging);

4.

Find the hover event below and replace it with the following code (new code is highlighted):
$("#slider, #prev, #next, #pagination").hover(function() { clearInterval(timer); pause = true; }, function() { timer = setInterval(rotate, speed); pause = false; }); [ 34 ]

For More Information: www.packtpub.com/jquery-2-0-animation-techniques-beginners-guide/book

Chapter 2

5.

Add the following code directly above our rotate() func on:
$("#pagination a").click(function(event) { event.preventDefault(); activeSlide = $(this).attr("rel") - 1; rotate(); });

The following screenshot illustrates the pagina on feature we added, along with the fourth image displayed a er clicking on the respec ve link:

What just happened?
The first thing we did was declare and set the new paging variable. Without this, we'll get nasty JavaScript errors in our code. Using a for loop, we defined our page variable, telling it to con nue looping un l page is less than the number of images in our set and then increment that newly defined variable by one using ++. The next line is the most complicated bit of code in our script so far, so s ck with me! A variable followed by += tells the variable to use what's already stored inside and to con nue adding on to the end. This method of stringing together values or strings is called concatena on.

[ 35 ]

For More Information: www.packtpub.com/jquery-2-0-animation-techniques-beginners-guide/book

Image Anima on

We then need to build the HTML structure of the pagina on links. We're building a series of seven <a> tags, one for each image in our group. To print the image numbers on the links, we'll use (page + 1). We're using + 1 because JavaScript numbers things on what's called a zero-index or zero-based numbering, which means instead of star ng at 1 when numbering a group or list of items, it starts with 0. This hasn't been a problem un l now (because we weren't prin ng out the value), but we now need to tell our script to start at 1 so that it displays the pagina on links properly. The last line of the for loop replaces the contents of #pagination and replaces it with the value stored inside the paging variable using html().
The html() method is used to get or set the HTML contents on the selected element(s).

Again, we need to expand our pause-on-hover func on to know to pause when we're hovering over our new #pagination element. If we don't do this, when you hover over the #pagination div, the images would con nue to rotate. We added another click func on ($("#pagination a").click) to handle our pagina on links. You'll no ce the same preventDefault() we used before so that our links don't add the hashtag (#) to our page URL when clicking on the pagina on links. The next line sets the activeSlide variable to the value of rel in our pagina on anchor tag and then subtracts by one. This is done because we set it to increment by one to offset the zero-index problem we saw in the third step. Finally, we added in the containing <div> element that'll hold all of our pagina on links.

Have a Go Hero – extending the image rotator further
In this example, we used fadeIn() and fadeOut() to rotate our images. Have a go at extending the example so that the script can detect the child elements that should be animated. Other ideas for extending the image rotator:

Have the script to set the child element dimensions dynamically, allowing the script to scale to fit the content Building the ability to show more than one element at a me Giving the current ac ve link in the pagina on bar a different look so that our user knows which image the rotator is currently on Adding in addi onal transi on effects (for example, slide)

 

[ 36 ]

For More Information: www.packtpub.com/jquery-2-0-animation-techniques-beginners-guide/book

Chapter 2

Pop quiz – altering variables and zero index
Q1. What does using ++ a er a variable do? 1. Merges the values of two variables together. 2. Tells the script to only allow adding to the variable and not subtrac ng. 3. Increments the variable by one. 4. Increments the variable by two. Q2. What does zero-index mean? 1. That JavaScript counts star ng with zero. 2. That a variable's default value is zero if not specifically defined. 3. A method in which an element's index is set to zero. 4. A method to set a variable's value to zero a er being used.

Summary
In this chapter, we looked at some of jQuery's most basic anima on methods. The fade methods are the simplest anima on methods found in jQuery, only anima ng the opacity of the selected element(s). The show(), hide(), and toggle() methods can also be used to perform anima ons but alter the dimensions of the element as well as its opacity. All of these methods are simple to use and require li le or no addi onal configura on in order to run. In the next chapter, we'll learn how to manipulate the background proper es on elements to create background anima ons.

[ 37 ]

For More Information: www.packtpub.com/jquery-2-0-animation-techniques-beginners-guide/book

Where to buy this book
You can buy jQuery 2.0 Animation Techniques Beginner's Guide from the Packt Publishing website: .
Free shipping to the US, UK, Europe and selected Asian countries. For more information, please read our shipping policy.

Alternatively, you can buy the book from Amazon, BN.com, Computer Manuals and most internet book retailers.

www.PacktPub.com

For More Information: www.packtpub.com/jquery-2-0-animation-techniques-beginners-guide/book