39,59 €
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. jQuery empowers you with creating simple as well as complex animations.
jQuery 2.0 Animation Techniques Beginner's Guide will teach you to understand 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.
In jQuery 2.0 Animation Techniques Beginner's Guide, each chapter starts with simple concepts that enable you to build, style, and code your way into creating beautifully engaging and interactive user interfaces.
With the use of wide range of examples, this book will teach you how to create a range of animations, from subtle UI effects (such as form validation animation and image resizing) to completely custom plugins (such as image slideshows and parallax background animations).
The book provides various examples that gradually build up your knowledge and practical experience in using the jQuery API to create stunning animations. The book uses many examples and explains how to create animations using an easy and step-by-step approach.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 367
Veröffentlichungsjahr: 2013
Copyright © 2013 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: December 2013
Production Reference: 1171213
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78216-964-2
www.packtpub.com
Cover Image by Jeremy Segal (<[email protected]>)
Authors
Adam Culpepper
Dan Wellman
Reviewers
Jeff Byrnes
Emil Lerch
Doug Sparling
Acquisition Editors
Harsha Bharwani
Akram Hussain
Lead Technical Editors
Mayur Hule
Larissa Pinto
Technical Editors
Iram Malik
Menza Mathew
Rahul U. Nair
Pratish Soman
Project Coordinator
Anugya Khurana
Proofreaders
Lauren Harkins
Elinor Perry-Smith
Indexer
Mehreen Deshmukh
Production Coordinator
Shantanu Zagade
Cover Work
Shantanu Zagade
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 his website (www.adamculpepper.net) or through Twitter (@adamculpepper).
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.
Jeff Byrnes is a software engineer with over 8 years of experience working in web development and operations. Educated as a musician at Berklee College of Music, self-taught as an engineer, he has experience ranges from frontend to backend and systems. HTML5, CSS3, JS, PHP, Git and version control, Puppet, Chef, Vagrant, Bash, Linux, deployment, automation, and analytics; these are all the technologies and skills with which he is experienced and proficient.
Currently, part of the Operations team at EverTrue, Jeff spends his days supporting the engineering team, providing automation, server monitoring and maintenance, workflow improvements, and deployment solutions, as well as providing help desk support to the company at large.
I'd like to thank Dale Cruse for connecting me with the opportunity to assist with this book's publication, and my better half Leah for supporting me as I worked on it.
Emil Lerch is a technical architect, leading teams to build web-based systems for enterprises since 1995. He lives in Portland, Oregon with his wife Kelly and children Kathryn and Jack. His blog is http://emilsblog.lerch.org and he can be reached on twitter @elerch.
My lovely wife and children for giving me the time to help review the book.
Doug Sparling works as a web and mobile software developer for Andrews McMeel Universal, a publishing and syndication company in Kansas City, MO. As long-time employee of the company, he has built everything from the GoComics Android app to registration, ecommerce systems, web services, and various web sites using Ruby on Rails. He's now busy building another site in Rails and porting a Perl-based e-mail system to Go. Some of the AMU properties include GoComics.com, PuzzleSociety.com, Doonesbury.com, and Dilbert.com.
He is also the directory of technology for the small web development firm called New Age Graphics (newage-graphics.com). After creating a custom CMS using C# and ASP.NET, all work has moved to WordPress since WordPress 3.0 was released, eliminating the need to ever run Windows again.
Doug is the author of a popular jQuery plugin, jClock.
Doug is a passionate advocate for WordPress and has written several WordPress plugins, can be found on the WordPress.org forums answering questions (and writing sample code) under the username "scriptrunner", and occasionally plays grammar nerd as a volunteer on the WordPress Codex Documentation team.
Other experience includes PHP, JavaScript, jQuery, Erlang, Python, Magento, and Perl. Doug was also the co-author for a Perl book (Instant Perl modules) and is a reviewer for other Packt books, including Mastering Android 3D Game Development and WordPress Web Application Development, as well as The Well Ground Rubyist, 2nd Edition and Learn Android in a Month of Lunches for Manning Publications.
In his less than ample spare time, Doug enjoys spending time with his family. Other passions include photography, writing music, hitting drums and cymbals with sticks, playing briscola, meditation, and watching countless reruns of Firefly, Buffy the Vampire Slayer, and Doctor Who.
Many thanks to Packt for giving me the opportunity to review a book on jQuery.
You might want to visit www.PacktPub.com for support files and downloads related to your book.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
http://PacktLib.PacktPub.com
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books.
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.
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.
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 left with a script worthy of your next development project.
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 animate() 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.
To get the most out of this book you should have some knowledge of front-end development, preferably including JavaScript. Experience with jQuery is also preferable, but is not essential as all techniques used in the book are discussed in full.
You should have a computer capable of running the latest browsers and preferably an Internet connection. A code editing development software package will be of help, but again is not essential provided you have a text editor of some kind.
This book is written for web designers and front-end developers who already have good knowledge of HTML and CSS. While not required, some experience with jQuery or JavaScript is helpful. If you want to learn how to animate the user interface of your web applications with jQuery, then this book is for you.
In this book, you will find several headings appearing frequently.
To give clear instructions of how to complete a procedure or task, we use:
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.
To send us general feedback, simply send an e-mail to <[email protected]>, and mention the book title through the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the erratasubmissionform link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website, or added to any list of existing errata, under the Errata section of that title.
Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <[email protected]> with a link to the suspected pirated material.
We appreciate your help in protecting our authors, and our ability to bring you valuable content.
You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.
Welcome to the jQuery 2.0 Animation Techniques Beginner's Guide. Over the course of the book we'll look at each and every method that produces or controls animations available in the jQuery JavaScript library. We'll see how the methods are used, the arguments they are able to accept, and the different behavior they produce. We'll also look at how to use a range of accompanying resources, including selected jQuery plugins and the jQuery UI library.
In this introductory chapter, we'll look at the following topics:
In 1989, CompuServe released GIF89a, an enhanced version of the popular GIF image format, which allowed a sequence of frames to be stored as a single image and played by supporting software.
The GIF format was already popular on what passed for the Internet in those days (remember, the World Wide Web didn't even exist until 1991) due to its small file size, lossless compression, and wide support. The enhanced version which allowed animations that anyone could create themselves, provided they had supporting software, quickly became popular.
In addition to animated GIFs, browser vendors added support for proprietary HTML elements that handled animation natively, such as the <blink> and <marquee> elements, which added different animated effects to text.
Neither of these elements was particularly attractive or successful, and the W3C, as well as leading industry accessibility and usability experts advised against their use in most cases. Different browsers at that time supported one or the other of these elements, but not both. Both elements were added by their respective vendors as part of the original browser wars.
In the late 1990s, popular browsers added support for a technique known as Dynamic HTML (DHTML), which allowed scripting languages to modify the contents of a page after the page had loaded. DHTML wasn't any single technology, but rather a collection of techniques (JavaScript, CSS, DOM, and so on) that worked together to enable a basic level of interactivity and/or animation.
In fact, DHTML made it possible to create quite advanced animations, but restrictions in the early implementations of the required technologies, as well as hugely varying browser support made DHTML tricky at best.
This era also saw the release and the rise of Flash (and Shockwave, a competing technology that was eventually subsumed by Macromedia—which was later acquired by Adobe in 2005), a vector and raster graphics format that allowed audio and video streaming, frame-by-frame animation, and a host of other features. Flash quickly became popular, and at the time of writing is still the number one format for web-based video, browser-based gaming, and advertising.
Gradual standardization of the DOM across (most) browsers, as well as the rise of JavaScript libraries such as jQuery, which abstracted away the differences that remained between browsers, have opened up animation to a much wider range of people than ever before. The term DHTML isn't often used these days because of its connotations with poor support between browsers, but the underlying principles and techniques that drive many interactive and animated sites remain similar.
Today, in addition to the animations made plausible and accessible by JavaScript libraries, we have much newer and much more exciting possibilities with CSS3 and native HTML elements such as the <canvas> element, which provides complete pixel-level control over an area of the page. We'll be looking at some CSS3 animation techniques, as well as the <canvas> element in more detail towards the end of the book. Flash-based animation is on the decline for the first time this century, and new technologies are poised on the horizon.
Modern operating systems use animations constantly to engage their users and to create a more compelling computing experience. When used in the right way, animations provide assistance to the users of the system, to lead and guide them through different tasks, provide context or feedback, and reinforce positive actions.
A good example of this is the way that applications are minimized in Windows 7 or OS X—the application appears to squish down into the icon on the taskbar/dock, which shows the user where to go when they want to return to the application. It's the simple details like this that can be most effective.
Good animations can lend an air of sleek professionalism to an interface and make it appear more advanced or more modern. Apple's iPhone (or iPad) is a perfect example—the seamless use of subtle animations and transitions within the operating system and its applications allow the user to connect with the device in a profoundly satisfying and immersive way. Anything that appears or disappears is faded smoothly in or out, and menus and content panels slide in or out from the top or the sides. Sudden events can unsettle or distract users, but a well-timed animation can help to make them aware that something is happening or something is about to happen.
Be warned though, badly executed, clumsy, or overly pointless animations can do the opposite, making your interface appear basic, poorly designed, or inferior. No animation can be better than poor animation. Even if your application works perfectly, superfluous animations can leave your users feeling frustrated and cause them to forgo your application or website.
Desktop computers and a rapidly growing number of mobile and handheld devices are easily powerful enough to handle quite complex animations, and with integrated hardware acceleration and more refined CSS3 and HTML5 making its way into the latest browsers, the possibilities of what can be achieved on the Web are increasing exponentially.
Animations can make a great impression and enhance the user experience in the following situations:
Too many animations in unnecessary places can be damaging. Try and avoid animations, or at least give them serious consideration, in the following situations:
Bear in mind that these are guidelines only, not laws which must be obeyed at all costs, and they are certainly not definitive. There are few situations where animations should never, ever be used and few situations where they must always be used.
Use your judgment to determine whether an animation is suitable for your application or page and its intended audience. If possible, give your users the chance to enable or disable animations based on their own personal preferences.
Before implementing an animation in our pages or applications, consider the following checklist of questions:
If you can answer yes to all of the above questions, the animation will probably be a positive feature. If you answered no to any of these questions, you probably need to stop and think about what you are trying to achieve by adding the animation, and whether or not it could be better achieved in some other manner.
jQuery (http://jquery.com) provides a range of animation methods natively, without the use of additional effect libraries or plugins. There are, however, many plugins contributed from the online community, including jQuery UI (http://jqueryui.com), the official UI library for jQuery, which extends jQuery's animation capabilities. Natively, jQuery provides methods that add sliding and fading behavior with minimal configuration and which work cross-browser. It also exposes methods related to managing the animation queue, and provides a means for creating custom animations that work on almost all numerical CSS styles. Over the course of this book, we'll look at every animation method that the library contains in detail. These methods are listed here with descriptions of each:
Methods
Description
animate()
It performs a custom animation of a set of CSS properties.
clearQueue()
It removes from the queue all items that have not yet been run.
delay()
It sets a timer to delay execution of subsequent items in the queue.
dequeue()
It executes the next function on the queue for the matched elements.
fadeIn()
It displays the matched elements by fading them to opaque.
fadeOut()
It hides the matched elements by fading them to transparent.
fadeTo()
It adjusts the opacity of the matched elements.
fadeToggle()
It displays or hides the matched elements by animating their opacity.
finish()
It stops the currently-running animation, removes all of the queued animations, and completes all of the animations for the matched elements.
hide()
It hides the matched elements.
queue()
It shows the queue of functions to be executed on the matched elements.
show()
It displays the matched elements.
slideDown()
It displays the matched elements with a sliding motion.
slideToggle()
It displays or hides the matched elements with a sliding motion.
slideUp()
It hides the matched elements with a sliding motion.
stop()
It stops the currently-running animation on the matched elements.
toggle()
It displays or hides the matched elements.
It's important to note that there are two properties that can change the Global jQuery Object. These are listed below:
Property
Description
jQuery.fx.interval
It is the rate (in milliseconds) at which animations fire.
jQuery.fx.off
It globally disables all animations.
All in all, it gives us a powerful and robust environment to easily add almost any type of animation that we can conceive.
Animation is also a popular theme for plugins, with many available plugins that bring different types of animations to our fingertips for instant implementation with minimal configuration. We'll look at several plugins later in the book.
So, that's the template file that we'll be referring to and using in the code examples throughout the book. Let's also take a moment to look at the folder structure that the example files use. Create a project folder and call it jquery-animation or any similar name. Within this, create three new folders and call them css, img, and js.
The HTML pages we create will go into the jquery-animation folder alongside the subfolders. All of the CSS files we create will go into the css folder, and all of the images that we use in the examples will go into the img folder. The jQuery library and any additional script files we use or create will go into the js folder. This is also the directory structure you'll find if you download and unpack the accompanying code archive containing all of the examples.
Each of the example files we'll create throughout the course of this book will rely on a common set of elements. Rather than repeatedly showing these same elements in every single code section and examples in the book, we'll take a look at them just once here:
Downloading the example code
You can download the example code files for all Packt books you have purchased from your account at http://packtpub.com. If you purchased this book elsewhere, you can visit http://packtpub.com/support and register to have the files e-mailed directly to you.
Save a copy of this file into the jquery-animation folder we just created and call it template.html. This is the base file that we'll use for every single example, so when we start working through the examples and I say add the following markup to the<body>of the template file, it means insert it directly between the opening <body> tag and the first <script> tag in the template file we just created in the preceding code. Whenever we add any JavaScript to the template file, it will be added within the anonymous function in the second <script> tag.
Let's take a look at what the template file contains. We start out with the HTML5 doctype declaration, as we'll be using plenty of HTML5 elements in our examples. We also set the lang attribute of the <html> element to en and the <meta> tag's charset attribute to utf-8, neither of which are strictly required, but are nevertheless best practice.
Next comes an empty <title> element, to which we can add the name of each example and a <link> element with an incomplete href, ready for us to add the name of the stylesheet that each example will use.
Since the versions prior to Internet Explorer 9 (IE9) don't support any HTML5 elements, we need to use Remy Sharp's html5shiv script to make this browser use HTML5 correctly. We can link to the online version of this file for convenience using a conditional comment that targets all of the versions of IE lower than version 9. Feel free to download html5.js and store it locally if you plan on playing with the examples in IE while disconnected from the Internet.
To get the most out of the examples throughout the book, it would probably be wise to upgrade to the latest stable release versions of the most common browsers, which at the time of writing are Firefox 24, Chrome 30, Safari 6, and Opera 17 (although expect these to change quite rapidly).
It's important to note that jQuery 2.0 doesn't support oldIE, meaning IE8 and below. For this reason, we won't be covering any browser compatibility fixes for those versions of IE.
If your project needs to be compatible with IE8 or older, you'll need to use jQuery 1.10 or below. Furthermore, if your project uses HTML5 elements and needs to be compatible with IE8 or below, you'll need to use html5shiv (https://code.google.com/p/html5shiv).
IE9 does support a lot of HTML5 and CSS3, so using the html5shiv file in general will only be required as long as IE8 holds its top spot as the world's most used browser. At the time of writing, Internet Explorer 8 had a market share of 21 percent worldwide according to NetMarketShare (http://netmarketshare.com
