jQuery Essentials - Troy Miles - E-Book

jQuery Essentials E-Book

Troy Miles

0,0
21,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Optimize and implement the features of JQuery to build and maintain your websites with minimum hassle

About This Book

  • Build dynamic websites efficiently without any performance issues
  • Learn to use existing jQuery plugins and or write your own for your websites
  • This is the most up-to-date book on the market at the moment, packed with detailed explanations and real-world examples

Who This Book Is For

Whether you are a beginner or an experienced developer who is looking for quick answers, you will find what you need in this book.

What You Will Learn

  • Quickly find and modify HTML DOM elements
  • Use animation to add flair to your site
  • Create your own events to decouple your application
  • Measure the performance of your website's JavaScript
  • Write unit tests to ensure that your application is behaving correctly
  • Use plugins to to save reinventing the wheel and enhance your site quickly
  • Use client-side validation on forms to prevent your users from sending bad data to your application
  • Write your own jQuery plugins in order to encapsulate your company's business logic

In Detail

JQuery is still the most popular JavaScript library. It is used in over 60% of the top websites on the Internet. It was written to make DOM manipulation (so, moving things around a web page) easier for developers. It acts through JavaScript to ascribe HTML elements to the DOM attributes. Because it is a library of predefined functions, all you need to start using jQuery is a working knowledge of the syntax and a reference for the functions available to you.

This practical guide shows you how to make the most of jQuery to boost the performance of your websites and applications. We start off with a quick glance through the basics of JQuery, followed by the explanation of JQuery selectors, filters, and DOM element manipulation. After this, you will learn how events and animations can be used to create and design beautiful and user-friendly sites. Next, you will be familiarized with Ajax functions to help you send and receive data from your server. Finally, we'll walk you through using built-in plugins and eventually create your own plugins for your websites.

By the end of this book, you will be able to to build robust and efficient websites successfully using JQuery.

Style and approach

This book takes a fast but thorough walk through jQuery. The goal is to get you writing fast and efficient jQuery quickly. It uses easy-to-read, jargon-free text and lots of ready-to-use code examples.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 230

Veröffentlichungsjahr: 2016

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

jQuery Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Support files, eBooks, discount offers, and more
Why subscribe?
Free access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. jQuery Part by Part
Life before jQuery
Why was jQuery created?
The major components of jQuery
The DOM selection
DOM manipulation
Events
Form
CSS and animation
Ajax
Helpers
Why are there two maintained versions of jQuery?
The difference between minified and un-minified versions
What is a content delivery network?
Summary
2. jQuery Selectors and Filters
jQuery selectors
The chapter code
Protocol-relative URLs
The jQuery object
Creating selectors
ID selectors
Class selectors
Tag selectors
Combining selectors
Descendent selectors
Attribute selectors
Creating basic filter selectors
Content filters
Using chaining to quickly and neatly continue queries
Summary
3. Manipulating the DOM
Dimensions and positions
Examples
Developer tools
Reading the size of the screen and elements
Classes and styles
The JSON object
Behavior classes
Attributes and properties
Keeping images proportional
Removing attributes and properties
Summary
4. Events
The ready event
Hooking events
Unhooking events
Namespacing events
The event handler
The event object
event.target
event.relatedTarget
event.type
event.which
event.metaKey
event.pageX and event.pageY
event.originalEvent
Passing data to an event
Event shorthand methods
Creating your own events
Triggering events
The death of the .live() and .die() methods
Looking deeper at .on()
Summary
5. Making Your Site Snazzy with jQuery
The importance of animations
Hiding and showing elements
.fadeOut()
.fadeIn()
.fadeToggle()
Sliding elements around
.slideUp()
.slideDown()
.slideToggle()
Creating custom effects
.animate()
.delay()
.queue(), .dequeue(), and .clearQueue()
.stop() and .finish()
jQuery.fx.interval and jQuery.fx.off
Using effects correctly
Summary
6. Better Forms with jQuery
Employing form methods
.submit()
.focus()
.blur()
.focusin() and .focusout()
.change()
.select()
Tooltips
Placeholder
Enabling and disabling elements
Validation
Filtering out unwanted characters
Summary
7. Talking to Your Server
Before jQuery
How jQuery helps us
Loading HTML – .load()
Loading JSON Data – .getJSON()
Loading and executing JavaScript – getScript()
Reading and writing data: jQuery.get() and .jQuery.post()
Helper methods
Creating query data – $.param()
Creating query data from a form – .serialize()
Creating an object from form data – .serializeArray()
Ajax events
When an Ajax request begins – .ajaxStart()
When an Ajax request completes – .ajaxStop()
When an Ajax request sends data – .ajaxSend()
When an Ajax request fails – .ajaxError()
When an Ajax request succeeds – .ajaxSuccess()
When an Ajax request finishes – .ajaxComplete()
Summary
8. Writing Code that You can Read Later
Separation of concerns
Breaking code into logical units
Using events to decouple code
Using unit tests
Why write unit tests at all?
Summary
9. Faster jQuery
Writing performance tests
Measuring jQuery
jQuery selectors
Using IDs over other selectors
Caching your selectors
Optimizing selectors
Right to left
Reducing overly specific selectors
Narrowing your search
Other jQuery optimizations
Updating to the latest version
Using the correct version of jQuery
Don't use deprecated methods
Using preventDefault() when appropriate
Never modify the DOM in a loop
jQuery isn't always the answer
Using document.getElementById
Using CSS
Summary
10. Benefiting from the Work of Others with Plugins
Finding plugins
Installing plugins
Updating a plugin
Uninstalling plugins
Adding a plugin
jQuery UI
jQuery UI Interactions
jQuery UI widgets
The jQuery UI widget factory
Writing your own plugin
Prep work
The plugin
Best practices
Preserve chaining
Use an IIFE
Add only one function to jQuery
Let the user theme it
Test, test, test
Document it
Minify it
Summary
Index

jQuery Essentials

jQuery Essentials

Copyright © 2016 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: January 2016

Production reference: 1220116

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78528-635-3

www.packtpub.com

Credits

Author

Troy Miles

Reviewers

Joydip Kanjilal

Anirudh Prabhu

Commissioning Editor

Edward Gordon

Acquisition Editor

Meeta Rajani

Content Development Editor

Kirti Patil

Technical Editor

Mohit Hassija

Copy Editor

Stuti Srivastava

Project Coordinator

Nidhi Joshi

Proofreader

Safis Editing

Indexer

Hemangini Bari

Graphics

Kirk D'Penha

Production Coordinator

Shantanu N. Zagade

Cover Work

Shantanu N. Zagade

About the Author

Troy Miles, a.k.a. the Rockncoder, began writing games in assembly language for early computers, such as the Apple II, Vic20, C64, and the IBM PC, over 35 years ago. Currently, he spends his days writing web apps for a Southern California-based automotive valuation and information company. During the nights and weekends, he can usually be found writing cool apps for mobile and Web or teaching other developers how to do that. He likes to post interesting code nuggets on his blog at http://therockncoder.com and videos on his YouTube channel at https://www.youtube.com/user/rockncoder. He can be reached at <[email protected]>.

About the Reviewers

Joydip Kanjilal is a Microsoft Most Valuable Professional in ASP.NET, speaker, and author of several books and articles. He has over 18 years of industry experience in IT with more than 10 years in Microsoft .NET and its related technologies. He was selected as MSDN Featured Developer of the Fortnight (MSDN) a number of times and also as Community Credit Winner at www.community-credit.com several times. He has authored the following books:

Entity Framework Tutorial Second Edition, Packt PublishingASP.NET Web API – Build RESTful Web Applications and Services on the .NET Framework, Packt PublishingVisual Studio Six in One, Wrox PublishersASP.NET 4.0 Programming, Mc-Graw Hill PublishingEntity Framework Tutorial, Packt PublishingPro Sync Framework, APRESSSams Teach Yourself ASP.NET Ajax in 24 Hours, Sams PublishingASP.NET Data Presentation Controls Essentials, Packt Publishing

Joydip has authored more than 300 articles for some of the most reputable sites, such as www.msdn.microsoft.com, www.code-magazine.com, www.asptoday.com, www.devx.com, www.ddj.com, www.aspalliance.com, www.aspnetpro.com, www.sql-server-performance.com, www.sswug.com, among others. A lot of these articles have been selected for www.asp.net: Microsoft's Official Site on ASP.NET.

He has years of experience in designing and architecting solutions for various domains. His technical strengths include C, C++, VC++, Java, C#, Microsoft .NET, Ajax, WCF, Web API, REST, SOA, Design Patterns, SQL Server, Operating Systems, and Computer Architecture.

He blogs at http://aspadvice.com/blogs/joydip and http://www.infoworld.com/blog/microsoft-coder. His website is located at www.joydipkanjilal.com. You can contact him on Twitter at https://twitter.com/joydipkanjilal, on Facebook at https://www.facebook.com/joydipkanjilal, and on LinkedIn at http://in.linkedin.com/in/joydipkanjilal.

Writing a book has always been a rewarding experience for me. My special thanks go to the entire Packt team for providing me with the opportunity to review this book. I am also thankful to the entire management team at SenecaGlobal for their continued support. My special thanks to my family for the continued inspiration and support. Thank you so much, all!

Anirudh Prabhu is a software engineer with over 5 years of industry experience.

He specializes in technologies such as HTML5, CSS3, PHP, jQuery, Twitter Bootstrap, and SASS, and he also has knowledge of CoffeeScript and AngularJS.

In addition to web development, he has been involved in building training material and writing tutorials for twenty19 (http://www.twenty19.com/) for the technologies that have been mentioned.

Anirudh has authored Beginning CSS Preprocessors With Sass, Compass, and Less, Apress (http://www.apress.com/9781484213483).

Besides Packt Publishing, he has been associated with Apress and Manning Publications as a technical reviewer for several titles.

www.PacktPub.com

Support files, eBooks, discount offers, and more

For support files and downloads related to your book, please visit www.PacktPub.com.

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.

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

Free access for Packt account holders

If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access.

Preface

jQuery Essentials helps you master the core capabilities of the most popular open source libraries ever created. You'll start by understanding the most fundamental parts of jQuery: selectors and filters. From selectors, you learn DOM manipulation, events, form validation, and more. To keep your site running fast, you'll have to measure its performance and improve it. Along the way, we'll show you lots of easy-to-remember best practices. In the end, you'll be able to make your site snazzier than ever with jQuery.

What this book covers

Chapter 1, jQuery Part by Part, provides a quick introduction to jQuery along with information on why it was created.

Chapter 2, jQuery Selectors and Filters, shows how to use jQuery's most fundamental capability: querying the Document Object Model, or DOM.

Chapter 3, Manipulating the DOM, walks you through the various ways in which jQuery can be used to modify and replace elements on screen.

Chapter 4, Events, explains how to make your site dynamic by using events to respond to interactions by users and systems.

Chapter 5, Making Your Site Snazzy with jQuery, takes a look at ways to use animation to make your site lively.

Chapter 6, Better Forms with jQuery, provides examples and explanations on using jQuery to process and validate user form data before sending it to a server.

Chapter 7, Talking to Your Server, dives into using Ajax to send and retrieve data from your server.

Chapter 8, Writing Code that You can Read Later, discusses ways to overcome jQuery's reputation of being the source of difficult-to-read spaghetti code.

Chapter 9, Faster jQuery, looks at some simple techniques to speed up your jQuery code and ways to measure its performance.

Chapter 10, Benefitting from the Work of Others with Plugins, introduces the jQuery UI and plugins, both of which make it easier to enhance your site using code written by others.

What you need for this book

To follow the code used in this book, all you will need is a programmer's text editor. A full-blown Integrated Development Environment (IDE) can be used, but it is not required. Most of the examples will run directly in a browser, with the exception of those covering Ajax. In order to run the Ajax examples, you'll need a web server or an IDE with a built-in server.

Who this book is for

Whether you are a beginner or an experienced developer who is looking for quick answers, you will find what you need in this book.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in 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 at www.packtpub.com/authors.

Customer support

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.

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. 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.

Errata

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 could 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 Errata Submission Form 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.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted 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.

Questions

If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.

Chapter 1. jQuery Part by Part

jQuery is hands down the most popular JavaScript library on the Internet. According to http://builtwith.com, it is used by over 87% of the websites that use a JavaScript library. That is an amazing amount of penetration. It is hard to believe that jQuery has only been around since 2006.

In this chapter, we will start to get you familiar with jQuery. We will cover the following topics:

Why was jQuery created?The major components of jQueryWhy are there two maintained versions of jQuery?What is a content delivery network?

Life before jQuery

2006 may not seem that long ago, but it is almost a lifetime in Internet years. If you don't agree, think about what kind of cellphone you had then, if you had one. At that time, the four most popular browsers were Internet Explorer, Firefox, Safari, and Opera. What about Chrome? It didn't exist yet, and it wouldn't come along until late 2008. Internet Explorer, used by over 80% of users, was by far the most popular.

At that time, Microsoft didn't seem too concerned with being standards-compliant. Why should they? They had over 80% of the market. If a website had to choose, they usually chose to work with IE. But the winds of change were already blowing. 80% might seem like an insurmountable lead, but two years ago, it was over 90%. The other browsers, led by Firefox, were slowly but surely chipping away at that lead. Lots of people, including developers, were switching to alternative browsers and they wanted websites that worked on them.

Unfortunately, writing web applications is tough now and it was worse then. JavaScript is not the friendliest programming language around. But JavaScript was not the problem; browsers were the problem. The same code ran on different browsers and behaved differently. On one, it ran perfectly; on another, it crashed, leaving users frustrated.

To understand how differences in browser implementations could result in lots of extra work for developers, let's take a look at implementing a JavaScript Ajax call. In 2006, the W3C (World Wide Web Consortium) standards didn't cover the XMLHttpRequest object that lies at the heart of all Ajax requests. Microsoft invented the technology way back in 1999 with Internet Explorer version 5. Unfortunately, they chose to implement it as an ActiveX control. ActiveX was a proprietary Microsoft technology, so there was no way other browsers could implement it in the same way. Mozilla, Safari, and Opera chose to implement it as an object attached to the global window. So, in order to add Ajax to a website that could work on all browsers, developers had to write, test, and maintain twice as much code as they should: a set of code for IE and another set of code for everybody else.

Are you thinking how hard could it be to detect whether the browser was IE and do something different? Well, you are right it isn't that hard to detect which browser your code is running, but it is hard to do it reliably because browsers can lie. According to the W3C standard, the way to detect the browser is simple:

window.navigator.appName

This property is supposed to return the name of the browser, but if you try it on Chrome, Safari, or Internet Explorer, they all return the same value, "Netscape". What gives? As I already said, browsers can lie.

Tip

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. 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.

During the 90s, websites began to detect which browsers were visiting them. At that time, there were really only three browsers: Netscape Navigator, Microsoft's Internet Explorer and the browser that started it all, NCSA Mosaic. Mosaic was created by the National Center for Supercomputing Applications at the University of Illinois Urbana-Champaign. At this time, the real battle for browser supremacy raged between Microsoft and Netscape. The companies fought by adding new features to their browsers.

One of the features that Netscape added to their browser was the frame element. It was very popular. Many websites of the time would only use the frame element if the browser was Netscape Navigator. They checked for Netscape either using window.navigator.appName or by window.navigator.userAgent. Navigator's code name was Mozilla, which was included in the user agent string. Later, when Microsoft added the frame element to IE, websites continued to not serve frame-based content to IE since they only identify the browser by name, not by feature detection. So, IE began to lie. It returned Netscape from window.navigator.appName and included Mozilla in its user agent. Now, for historical compatibility, many other browsers lie too.

There are two ways to deal with browser compatibility issues. The first way is the one we've already shown: browser detection. Browser detection is tougher than you think, and it can have unintended side effects, just like the failure of websites to serve frames to IE even after it supported them. The second technique is feature detection, also known as property sniffing. Before you use a feature, you should make sure the browser supports it. While this is usually more difficult code to write, it is much more beneficial to users. If the feature isn't supported in one version of a browser, it may be supported in the next. Feature detection is the method used in jQuery.

Tip

Best practice

Use feature detection, not browser detection. If you need to write code to detect a feature yourself instead of using jQuery or some other third-party solution such as Modernizr, always use feature detection and never use browser detection.

Why was jQuery created?

One of the major reasons for the creation of jQuery was to free developers from having to check the entire myriad of features, which were implemented differently on the available browsers. In fact, jQuery's motto is "write less, do more". One of the goals of jQuery is to free developers from writing plumbing code and concentrate on adding functionalities to their websites instead.

The major components of jQuery

Looking at the jQuery API page, http://api.jquery.com, for the first time can be mind-numbing. It lists over 300 different methods. Don't freak out; there is a method to the madness. Most of the API methods can be divided into just a few categories.

The DOM selection

These are the methods that give jQuery its name. They help find the element or elements that you are looking for in the document object model (DOM). If you know browser JavaScript, you are probably thinking what is the big deal? It has always been possible to query the DOM. There are document.getElementById, document.getElementsByClassName, and so on. But the interface of jQuery is much cleaner than any of these methods. jQuery uses CSS-style selectors to parse the DOM, and it consistently returns a jQuery object as an array of zero or more elements.

The document methods return different things depending on which method you call. If you call document.getElementById, it returns either an element object or null if the element is not found. For document.getElementsByClassName, it returns HTMLCollection, an array-like object.

DOM manipulation

Once you have found an element, you will usually want to modify it somehow. jQuery has an extensive set of manipulation methods. The built-in document methods can't compare. jQuery's methods allow you to delete or replace markups. You can also insert a new markup before, after, or surrounding the old markup.

Events

Being able to handle events is crucial to creating a dynamic website. While modern browsers all pretty much follow the standards, this wasn't the case a few years ago. jQuery makes it possible to support both modern and old browsers from the same code base.

Form

A good number of websites on the Internet have one or more forums to send user information back to a web server. These methods make it easier to send the information back to a server.

CSS and animation

CSS methods are convenience methods and aid the handling of classes and the locations and dimensions of elements. Unlike the built-in JavaScript methods, they do far more than simply reading the class attributes' string; they allow you to add, remove, toggle, and check for the presence of a class.

Animation methods are simple but add polish to your website. No longer do you have to settle for a markup, which appears or disappears; now, it fades in or out or even slides in or out. And if you are so inclined, you can use jQuery's effect framework to create your own custom animation effects.

Ajax

As we've already discussed, Ajax is one of the main features of jQuery. Even if you don't need to support legacy browsers, jQuery's Ajax methods are much cleaner than those of the browser. They also have built-in support for asynchronous success and error functions and even return a JavaScript promise object.

Helpers

The final, main group of jQuery methods is about helper functions, such as .each(), to iterate over a collection. jQuery also adds methods to determine the type of a JavaScript object, and it functions strangely missing from the language. Plus, it adds other methods that don't fit neatly into a category.

Why are there two maintained versions of jQuery?

After nearly 7 years of development, jQuery was beginning to show its age. The 1.8 version was a major release and included a rewrite of the Sizzle Selector Engine and improvements to the animations, but more was needed. There were some inconsistencies in the interface, there were lots of deprecated methods, and there was lots of code in need of thorough cleaning. So, the version 1.9 release consisted of jQuery and the jQuery Migrate plugin.

The jQuery development team believed 1.9 was such a huge change that they created the jQuery Migrate plugin to help ease the transition. The Migrate plugin included all of the deprecated methods, which sounds weird, but in its development version, it console logged the use of deprecated methods. This gave developers a working site and a way to know what things needed to be fixed. The production version doesn't do any extra logging.

The 2.0 version came out a few months later, and it brought a friend. The development team, continuing to address both the platform's weight and speed, decided to drop support for all versions of Internet Explorer below 9. A great deal of code in jQuery was written specifically for the quirks in older versions of Internet Explorer. The difference was dramatic. The minimized version of jQuery 1.10 is 93 KB, while the minimized version of jQuery 2.0 clocks in at 83 KB, a nearly an 11% reduction in size.

So, for now and the foreseeable future, there will be two versions of jQuery: the 1.x version that supports most browsers, including Internet Explorer versions 6, 7, and 8. The 2.x version supports all modern browsers, including IE versions 9 and higher. It is important to note that both versions have the same API, though their internals are different.

The difference between minified and un-minified versions

For each