Sams Teach Yourself HTML, CSS & JavaScript Web Publishing in One Hour a Day

(singke) #1
ptg16476052

500 LESSON 18: Using jQuery


What Are JavaScript Libraries?


In this book, I’ve talked about browsers and incompatibilities between them. The popular
browsers differ in their support for HTML and CSS and in their support for JavaScript.
Unlike CSS and HTML, though, JavaScript can actually be used to solve the problem of
incompatibilities in JavaScript implementations. You can write code that detects which
browser is being used or even the specific capabilities of the browser and then add logic
to make sure the program works correctly for whatever environment that it’s in.
For example, some browsers allow you to retrieve elements from the document by class
name using the getElementsByClassName() method , and others do not. If your script
depends on that method, it will break in some browsers. You can work around the prob-
lem by checking to see whether the method exists before you use it, and if it doesn’t,
using another technique that works in the browsers that don’t support it.
JavaScript libraries were created by people who had to do this sort of thing too many
times and decided to package up all of these kinds of workarounds to create a simpler
interface to common functionality that hides all the incompatibilities of the various
browsers. In doing so, the authors also added many other features to make life more con-
venient for JavaScript developers. The most popular JavaScript libraries make it easier
to bind code to events, select elements on the page to act on in your programs, and even
make calls to the server from JavaScript to dynamically change elements on the page,
using a technique referred to as AJAX.
You might have noticed that I am referring to JavaScript libraries as a group. That’s
because there are a number of libraries that provide roughly the same set of features.
They were all independently developed and work differently from one another, and each
has its own set of advantages and disadvantages. If you’re starting from scratch, choosing
between them is a matter of taste.

Getting Started with jQuery


Entire books are published about each of the popular JavaScript libraries, so it would be
foolish to try to cover them all in this lesson. Instead, I’m going to focus on introducing
jQuery. I’ve chosen it mainly because it’s the easiest library to get started with, especially
if you already know CSS. Even if you don’t wind up using jQuery, you’ll still get an idea
of how JavaScript libraries work by reading this section. You’ll just have to follow up by
digging into the documentation to learn how to apply the same concepts with the library
that you use instead.
Free download pdf