31,19 €
jQuery is awesome for designers ñ it builds easily on the CSS and HTML you already know and allows you to create impressive effects with just a few lines of code. However, without a background in programming, JavaScript ñ on which jQuery is built ñ can feel intimidating and impossible to grasp. This book will show you how simple it can be to learn the basics and then extend your capabilities by taking advantage of jQuery plugins.jQuery for Designers offers approachable lessons for designers with little or no background in JavaScript. The book begins by introducing the jQuery library and a small and simple introduction to JavaScript. Then you'll step through a few simple tasks to get your feet wet before diving into using plugins to quickly and simply add complex effects with just a few lines of code.You'll be surprised at how far you can get with JavaScript when you start with the power of the jQuery library and this book will show you how. We'll cover common interface widgets and effects such as tabbed interfaces, custom tooltips, and custom scrollbars. You'll learn how to create an animated navigation menu and how to add simple AJAX effects to enhance your site visitors' experience. Then we'll wrap up with interactive data grids which make sorting and searching data easy.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 372
Veröffentlichungsjahr: 2012
Copyright © 2012 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 author, 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: April 2012
Production Reference: 1180412
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-84951-670-9
www.packtpub.com
Cover Image by Rakesh Shejwal (<[email protected]>)
Author
Natalie MacLees
Reviewers
Mark Tapio Kines
Tammy C. Wilson
Acquisition Editor
Sarah Cullington
Lead Technical Editor
Chris Rodrigues
Technical Editors
Manasi Poonthottam
Ankita Shashi
Manali Mehta
Sakina Kaydawala
Copy Editor
Laxmi Subramanian
Project Coordinator
Kushal Bhardwaj
Proofreader
Steve Maguire
Indexers
Hemangini Bari
Tejal Daruwale
Production Coordinator
Prachali Bhiwandkar
Cover Work
Prachali Bhiwandkar
Natalie MacLees is a frontend web developer and UI designer. She spends her days on the product team at Geni (geni.com), a Los Angeles-based startup that is crowdsourcing the creation of a single family tree of the world. Together with Noel Saw she heads up the Southern California WordPress User's Group (socalwp.org), organizing WordPress meetups, help sessions, and workshops. In 2010, she worked as a technical reviewer on WordPress 3 Complete by April Hodge Silver. She makes her online home at nataliemac.com.
Her obsession with the Web began when she bought her first computer in 1996 and promptly used it to build her first website. She spends the few moments she manages to be offline each day watching baseball, crafting, reading, baking, bellydancing, collecting Hello Kitty items, and avoiding avocados and olives at all costs. She lives in Los Angeles in eternal hope of developing so many freckles, they'll all touch and make a tan.
Gracious thanks first and foremost to John Resig and the rest of the jQuery team for creating and sharing such a useful and elegant library with the rest of us. Thank you to Houman Allahverdi for being patient while I spent so many hours at the computer, telling him to turn off the TV so I could concentrate. Thank you to Anna Motzer, Mark Tapio Kines, Tammy Wilson, Kimberly Wilkinson, Vanesa Rey, Marlene Angel, Trisha Marcy, Ed Doolittle, LeHang Huynh, Marco Hernandez, McCabe Russell, Teresina Goheen, and Ninno DePatrick for their support, advice, and cheerleading —I couldn't ask for better friends. Thank you to my sisters, Stefanie Elder and Bethany MacLees for being properly impressed that somebody wanted me to write a book. Thank you to my mom, Patricia Demby, and stepfather, John Demby, for being proud of me no matter what. And finally, thank you to Diane Colella Jones for believing in me, even before I did.
Mark Tapio Kines has been designing websites professionally since 1995. As a lead designer/art director, his highly diverse client list includes Universal Pictures, Sega, Conan O'Brien, Caltech, and the Internal Revenue Service. He was also the longtime art director for Paramount Pictures' online division in Hollywood. Aside from web design, Mark is an award-winning filmmaker, having written and directed two independent features and several shorts. Today he maintains a busy freelance career as a writer, designer, filmmaker, animator, and creative consultant.
Tammy Wilson has been programming in various languages for many years. She has been creating websites since 2006, when she got tired of the corporate IT world and struck out on her own. Tammy has been focusing on WordPress since Natalie MacLees introduced her to the popular open-source platform. Tammy has a Bachelor of Science degree in Computer Science from California State University, Fullerton.
When not working on websites, she enjoys training and competing with her dogs in agility as well as teaching agility classes. She is also interested in writing iOS Apps.
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.
Thank you for reading jQuery for Designers. This book is intended for designers who have a basic understanding of HTML and CSS, but want to advance their skill set by learning some basic JavaScript. Even if you've never attempted to write JavaScript before, this book will step you through the process of setting up some basic JavaScript and accomplishing common tasks like collapsing content, drop-down menus, slideshows, and more, all thanks to the jQuery library!
Chapter 1, Designer, Meet jQuery, is an introduction to the jQuery library and JavaScript. You'll learn about jQuery's rise to fame, why it's so great for designers, and how it can help you create some fancy special effects without having to learn a lot of code. This chapter also includes a gentle and small introduction to JavaScript, and steps you through writing your first JavaScript code.
Chapter 2, Enhancing Links, walks you through some basic enhancements to links. You'll learn how to use jQuery to open a link in a new window, how to add icons to links, and how to turn a list of links into a tabbed interface.
Chapter 3, Making a Better FAQ Page, will introduce you to collapsing and showing content, as well as traversing an HTML document to move from one element to another. In this chapter, we'll set up a basic FAQ list, then work on progressively enhancing it to make it easier for our site visitors to use.
Chapter 4, Building Custom Scrollbars, is our first look at jQuery plugins. We'll use the jScrollPane plugin to create custom scrollbars that work as expected in several different browsers. We'll take a look at setting up scrollbars, customizing their appearance, and implementing animated scrolling behavior.
Chapter 5, Creating Custom Tooltips, takes a look at using the qTip plugin to replace the browser's default tooltips with custom tooltips. Then we take that a step further and create custom tooltips to enhance a navigation bar and use the tooltips to show extra content.
Chapter 6, Building an Interactive Navigation Menu, steps you through setting up fully functioning and visually stunning drop-down and fly-out menus. We step through the complex CSS required to get these types of menus working, use the Superfish plugin to fill in features missing from pure CSS solutions, and then take a look at customizing the appearance of the menus.
Chapter 7, Navigating Asynchronously, introduces Ajax and shows how to turn a simple website into a single page web app with a bit of jQuery. First, we set up a simple example, then step through a more full-featured example that includes support for incoming links and the back button.
Chapter 8, Showing Content in Lightboxes, will step you through showing photos and slideshows in a lightbox using the Colorbox jQuery plugin. Once we get the basics down, we'll also take a look at using the Colorbox plugin to create a fancy login, play a collection of videos, and even set up a single-page website gallery.
Chapter 9, Creating Slideshows, walks you through several different approaches to creating image slideshows. First, we step through a basic crossfade slideshow example built from scratch. Then we'll look at using the CrossSlide plugin, the Nivo Slider plugin, and the Galleriffic plugin to create different types of slideshows.
Chapter 10, Featuring Content in Carousels and Sliders, introduces carousels, news tickers, and sliders, all built with the help of the jCarousel jQuery plugin. We'll create a horizontal carousel, a vertical news ticker, and a featured content slider. Then, we'll take a look at how plugins can be extended even further when we integrate a slideshow to be used with a carousel.
Chapter 11, Creating an Interactive Data Grid, steps you through turning a simple HTML table into a fully-interactive data grid, allowing your site visitors to page through the table, search for entries, and sort by different columns.
Chapter 12, Improving Forms, takes a look at how forms can be improved. This chapter walks you through properly setting up an HTML form using some of the latest HTML5 form elements. Then we enhance the form by placing the cursor in the first field, using placeholder text, and validating the site visitor's form entries. Finally, we take a look at the Uniform jQuery plugin which allows us to style even the most stubborn and challenging form elements to achieve a consistent look for our forms across browsers.
You'll need a text editor for creating HTML, CSS, and JavaScript. Some great free options are TextWrangler for Mac or Notepad++ for Windows. There are also many other options available and you can feel free to use your favorite text editor for any of the examples in this book.
You'll also need a browser. My personal favorite is Google Chrome, which includes some really helpful debugging tools for both CSS and JavaScript. Again, you can feel free to use your favorite browser for the examples in the book.
If you want to create images for your own designs, then Adobe Photoshop and Adobe Illustrator will be helpful, though they are not strictly necessary. Any images needed to set up the examples used in this book are included in the sample code.
This book is for designers who have the basic understanding of HTML and CSS, but want to extend their knowledge by learning to use JavaScript and jQuery.
In this book, you will find several headings appearing frequently.
To give clear instructions of how to complete a procedure or task, we use:
Instructions often need some extra explanation so that they make sense, so they are followed with:
This heading explains the working of tasks or instructions that you have just completed.
You will also find some other learning aids in the book, including:
These are short multiple choice questions intended to help you test your own understanding.
These set practical challenges and give you ideas for experimenting with what you have learned.
You will also find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.
Code words in text are shown as follows: " The jQuery object's filter() method will allow us to filter a previously selected set of elements."
A block of code is set as follows:
When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:
New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "Some argue that opening a link in a new window breaks the expected behavior of the Back button and should be avoided."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
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 via the subject of your message.
If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or e-mail <[email protected]>.
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/support, 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 on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.
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.
You might have heard quite a lot about jQuery over the past couple of years—it's quickly become one of the most popular code packages in use on the Web today. And you might have wondered what all the fuss was about.
Whether you've tried to figure out JavaScript before and have thrown up your hands in frustration or have been too intimidated to even give it a go, you'll find that jQuery is a wonderfully approachable and relatively easy to learn approach to getting your feet wet with JavaScript.
In this chapter, we will cover:
jQuery is a JavaScript library. That means that it's a collection of reusable JavaScript code that accomplishes common tasks—web developers often find themselves solving the same problems over and over again. Instead of engineering a solution from scratch each time, it makes sense to collect up all those useful bits into a single package that can be included and used in any project. The creators of jQuery have written code to smoothly and easily handle the most common and most tedious tasks we want to accomplish with JavaScript—and they've ironed out all the little differences that need to be worked out to get the code working in different browsers.
It's important to remember that jQuery is JavaScript, not a language of its own. It has all the same rules and is written the same way as JavaScript. Don't let that frighten you away—jQuery really does make writing JavaScript much easier.
jQuery's official tag line is Write Less, Do More. That's an excellent and accurate description of the jQuery library—you really can accomplish amazing things in just a few lines of code. My own unofficial tag line for jQuery is Find Stuff and Do Stuff To It because finding and manipulating different parts of an HTML document is extremely tedious with raw JavaScript and requires lines and lines of code. jQuery makes that same task painless and quick. Thanks to jQuery, you can not only quickly create a drop-down menu—you can create one that's animated and works smoothly in many different browsers.
So just what is it about jQuery that makes it so easy to learn, even if you have limited or no experience with JavaScript?
The first thing you'll often do in a jQuery script is select the elements you'd like to work with. For example, if you're adding some effects to a navigation menu, you'll start by selecting the items in the navigation menu. The tools you use for this job are selectors—ways to select certain elements on the page you want to work with.
jQuery borrowed selectors from CSS all the way up through CSS3 and they work even in browsers that don't support CSS3 selectors just yet.
Even though CSS offers a pretty robust set of selectors, jQuery adds a few more, all on its own, to make just the elements you need easy to work with.
If you already know how to do things such as make all the level 1 headings blue or make all the links green and underlined, then you'll easily learn how to select the elements you'd like to modify with jQuery.
If you want to create new elements or modify existing elements with raw JavaScript, you better crack your knuckles and get ready to write lots and lots of code—and it won't make all that much sense, either.
For example, if we wanted to append a paragraph to our page that said This page is powered by JavaScript, we would have to first create the paragraph element, then assign the text that should be inside the paragraph to a variable as a string, and finally append the string to the newly created paragraph as a text node. And after all that, we would still have to append the paragraph to the document. Phew! (Don't worry if you didn't understand all of that—it was just to illustrate how much work and code is required to do something this simple.)
With jQuery, adding a paragraph to the bottom of our page is as simple as:
That's right—you just append a bit of HTML directly to the body and you're all set. I bet that without understanding JavaScript at all, you can read that line of code and grasp what it's doing. This code is appending a paragraph that reads This page is powered by jQuery to the body of my HTML document.
You've got better things to do than to sit and write lines and lines of code to add fade in and fade out effects. jQuery provides you with a few basic animations and the power to create your own custom animations right out of the box. Let's say I wanted to make an image fade into the page:
Yep, that's it—one little line of code in which I select my image and then tell it to fade in. We'll see later in the chapter exactly where this line of code will go in your HTML page.
As I've said earlier, web developers often find themselves solving the same problems over and over again. You're likely not the first person who wanted to build a rotating image slideshow, an animated drop-down menu, or a news ticker.
jQuery has an impressively large library of scripts available freely—scripts to create tooltips, slideshows, news tickers, drop-down menus, date pickers, character counters, and on and on. You don't need to learn how to build all these things from scratch—you just have to learn how to harness the power of plugins. We'll be covering some of the most popular jQuery plugins in this book, and you'll be able to take what you've learned to use any plugin in the jQuery plugin library.
jQuery is an open source project—that means it's being collectively built by a team of super-smart JavaScript coders and is freely available for anyone to use. The success or failure of an open source project often depends on the community behind the project—and jQuery has a large and active community supporting it.
That means that jQuery itself is being constantly improved and updated. And on top of that, there are thousands of developers out there creating new plugins, adding features to existing plugins, and offering up support and advice to newcomers—you'll find new tutorials, blog posts and podcasts on a daily basis for just about anything you want to learn.
In this section, I am going to cover a few basics of JavaScript that will make things go more smoothly. We're going to look at a little bit of code and work through how it works. Don't be intimidated—this will be quick and painless and then we'll be ready to get on with actually doing something with jQuery.
There are a few different schools of thought when it comes to enhancing your HTML pages with JavaScript. Let's talk about some of the things we should consider before we dive into the cool stuff.
Progressive enhancement and graceful degradation are essentially two sides of the same coin. They both mean that our page with its impressive JavaScript animations and special effects will still work for users who have less capable browsers or devices. Graceful degradation means that we create our special effect and then make sure it fails gracefully if JavaScript is not enabled. If we take the progressive enhancement approach, we'll first build out a bare bones version of our page that works for everyone, and then enhance it by adding on our JavaScript special effects. I tend to favor the progressive enhancement approach.
Why should we care about users who don't have JavaScript enabled? Well, one of the Web's biggest users—search engines—do not have JavaScript capabilities. When search engines are crawling and indexing your pages, they will not have access to any content that's being loaded into your pages by JavaScript. That's often referred to as dynamic content, and it won't be indexed or found by search engines if it can't be reached with JavaScript disabled.
We're also in an era where we can no longer count on users accessing the web pages we build with a conventional desktop or laptop computer. We're quick to think of smart phones and tablets as the next candidates, and while they are very popular, they still only account for a tiny fraction of Internet access.
People are accessing the Web from gaming consoles, e-book readers, Internet-enabled televisions, a huge variety of mobile devices, and probably hundreds of other ways. Not all of these devices are capable of executing JavaScript—some of them don't even have color screens! Your number one priority should be making sure that your content is available to anyone who asks for it, no matter what device they happen to be using.
To accomplish this task of making our content available to as wide an audience as possible, we have to think of our web pages in three separate and distinct layers: content, presentation, and behavior.
Content is the meat of our web page—it's the text or the audio or video that we're most interested in presenting on our page, so this is where we start.
Mark up your content with clean, simple HTML code. Use HTML elements the way they were intended to be used. Mark up headings with heading tags, paragraphs with paragraph tags, lists with list tags, and save tables for tabular data.
Browsers have built-in styles for these basic HTML tags—headings will be larger type and probably bolded. Lists will have bullets or numbers. It might not look very fancy, but it's readable and accessible to anyone.
The presentation layer is where we start to get fancy. This is where we introduce CSS and start applying our own styles to the content we've created. As we style our page, we might find that we have to go back into our HTML and add some new containers and markup to make things such as multi-column layouts possible, but we should still strive to keep our markup as simple and as straightforward as we can.
Once our page has all of our content properly marked up and is styled to look the way we like, now we can think about adding in some interactive behavior. This is where JavaScript and jQuery come in. This layer includes animations, special effects, AJAX, and more.
We're ready to include the magic of jQuery into a project, but first we need to download it and figure out how to get it attached to an HTML page. Here, we'll walk through getting a sample HTML file started, and all the associated files and folders we'll need to work through a sample project set up. Once we're finished, you can use this as a template for all the future exercises in the book.
Earlier, I described the three layers of an HTML document—content, presentation, and behavior. Let's take a look at how we can set up our files for these three layers:
The styles represent our presentation layer. We'll keep all of our styles in this file to keep them separate. Likewise, create a folder called images to hold any images we'll use.
Next, create a folder called scripts to hold our JavaScript and jQuery code. Inside the scripts folder, create an empty JavaScript file called scripts.js.The JavaScript we write here represents our behavior layer. We'll keep all of our JavaScript in this file to keep it separate from the other layers.
Now, inside the jQueryForDesigners folder, create a new HTML page—very basic as follows:Save this file as index.html. The HTML file is our content layer—and arguably the most important layer; as it's likely the reason site visitors are coming to our website at all.
Next, we'll attach the CSS and JavaScript files that we made to our HTML page. In the head section, add a line to include the CSS file:And then head down to the bottom of the HTML file, just before the closing </body> tag and include the JavaScript file:
As these files are just empty placeholders, attaching them to your HTML page won't have any effect. But now we have a handy place to write our CSS and JavaScript when we're ready to dive into an exercise.
Note that it's perfectly fine to self-close a <link> element, but a <script> element always needs a separate closing </script> tag. Without it, your JavaScript won't work.
Here's what my folder looks like at this point:
Now we have to include jQuery in our page. Head over to http://jquery.com and hit the Download(jQuery); button:You'll notice you have two options under Choose Your Compression Level. You'll always want to check the Production checkbox. This is the version that's ready to use on a website. The Development version is for experienced JavaScript developers who want to edit the source code of the jQuery library.
Clicking on the Download button will open the production jQuery file in your browser window, and it looks a little bit scary, as follows:Don't worry, you don't have to read it and you definitely don't have to understand it. Just go to your browser's file menu and choose Save Page As... or right-click on the page and select Save As and then save the file to your hard drive, inside the scripts folder we created. By default, the script will have the version number in the file name. I'm going to go ahead and rename the file to jquery.js to keep things simple.Now we just have to include our jQuery script in our page, just like we included our empty JavaScript file. Go to the bottom of your practice HTML file, just before the <script> tag we created earlier and add a line to include jQuery:You won't notice any changes to your HTML page—jQuery doesn't do anything on its own. It just makes its magic available for you to use.
There is nothing wrong with downloading and using your own copy of jQuery, but you do have another option available that can help to improve the performance of your websites. That's to use a CDN-hosted copy of jQuery.
In case you don't know, a CDN is a Content Delivery Network. The premise behind a CDN is that files download faster from the servers that are physically closer to a site visitor's location. So, for example, if you're in Los Angeles, California, a copy of jQuery that's on a server in Phoenix, Arizona will download faster than a copy that's on a server in New York City. To help this along, a CDN has a copy of the same file on lots of different servers all around the world. Each time a site visitor requests a file, the CDN smartly routes their request to the closest available server, helping to improve response times and overall site performance.
