Getting started with jQuery

1. WHAT JQUERY IS GOOD AT

Without a doubt, one of the strong points of using jQuery is how it diminishes many cross­browser concerns. Without it, writing cross-browser-compatible JavaScript code is a tedious, and unnecessary, exercise. It’s difficult not to marvel at how much time is saved getting things running in both IE and Firefox with jQuery. The core is also excellent at traversing the DOM tree and selecting elements. It’s also very lightweight, with the production version standing at 29 kb, which is minified and compressed. That’s a lot of kick for a small file. When debugging and testing, you’re better off using the uncompressed development version, which is 212 kb.

jQuery is also good at handling fairly complex JavaScript code with relatively little code. This was one of my initial attractions to the framework. For a newbie trying to learn the “ropes” with Ajax, jQuery lowers the learning curve. Understanding what’s going on under the hood is important, but as a first step, using $.ajax() isn’t a bad start.

An active user community means active support. Googling jQuery returns about 36.8 million results at the time of this writing. New official and third-party plugins come out every day, extending its core functionality. With so many projects dependent upon jQuery, it’s easy to find help online (and really cool print books too).

With that said, it might be overkill in some cases. Remember that including the jQuery library has some overhead, even if it’s small, and if you’re only using the selectors to get an element by its ID, then the built-in JavaScript capability of the browser is enough. But, if you plan to build a feature- rich, dynamic Ajax web application, jQuery is the way to go.

2. HARDWARE AND BROWSER REQUIREMENTS

Your requirements for running jQuery are very light: a computer, smart phone, or device capable of running a modern browser. The browser requirements are fairly liberal as well. The official site lists the following browsers that are supported as well:

  • Firefox 2.0+
  • Internet Explorer 6+
  • Safari 3 +
  • Opera 10.6+
  • Chrome 8+

The following browsers are known to give problems:

  • Mozilla Firefox 1.0.x
  • Internet Explorer 1.0-5.x
  • Safari 1.0-2.0.1
  • Opera 1.0-9.x
  • Konqueror

Quirksmode has a great page detailing the CSS compatibilities of different browsers, including CSS3. To find out more visit www.quirksmode.org/css/contents.html.

3. OBTAINING JQUERY AND JQUERY UI

Besides the links found on jquery.com for downloading the production and development versions, you have a few other options for obtaining or linking to the jQuery libraries. You can link to several content delivery networks (CDNs) in your applications such as Google, Microsoft, and the jQuery CDN that are mentioned on the official jQuery website.

The following code illustrates obtaining jQuery from the various available CDNs. Simply add a script tag, point it at the proper URL and you’re ready to go.

<script src=uhttps://googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js”></script>

<script src=”http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js”></script>

<script src=”http://code.jquery.com/jquery-1.7.1.min.js”></script>

Code snippet is from cdns.txt

A Git repository also hosts a “Work in Progress,” or WIP, build. This is a constantly revised development version, which is not meant for production. The WIP build is generated every minute. To use this bleeding-edge version you can directly link from http://code.jquery.com/jquery- git.js or you can clone the Git repository to build jQuery from scratch. The following code shows the Git command used to clone the latest version of the library.

$ git clone https://github.com/jquery/jquery.git jquery-build

In order to build, you’ll need GNU to make 3.8+ and Node.js .2+. After cloning the repo, change into the jQuery directory and execute the make command. This will generate a complete minified version of jQuery, and run through JSLint (more on JSLint later). If you don’t want this, run make jquery instead of make.

4. “HELLO WORLD” EXAMPLE

No programming text is complete without the ubiquitous “Hello World” program:

<html>

<head>

<script

src=” https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js”>

</script>

<script

jQuery(document).ready(function(){

alert(‘Hello World’);

});

</script>

</head>

<body>

</body>

</html>

Code snippet is from hello-world.txt

In a nutshell, a minified version of jQuery is loaded from an online CDN over the Web. The jQuery function is called with the document object passed in as a parameter. This creates a jQuery wrapper object which has a ready() method whose only argument is a function. This function is invoked when the browser has finished converting the HTML on the page into the document object model (or DOM). At that moment, your function displays an alert, “Hello World.” There’s much more going on here than meets the eye and if you don’t understand yet, don’t worry. Chapter 2 revisits JavaScript, and most importantly, JavaScript’s way of managing functions. There you’ll understand the reason for the anonymous function. In Chapters 3 and 4, you see the concepts behind the jQuery wrapper, and using selectors to get elements from the DOM. Then you’ll have a better idea of what jQuery(document) means. Finally, in Chapter 5 you get acquainted with event handling, such as the aforementioned .ready(). So, although the code written for this example is rather brief, it’s rather dense and will be unpacked later.

JAVASCRIPT CONVENTIONS USED IN THIS BOOK

Throughout this book, we’ll stick to a small subset of the Google JavaScript Style Guide found at http://google-styleguide.com/svn/trunk/javascriptguide.xml and the jQuery Core Style Guidelines found at http://docs.jquery.com/jQuery_Core_Style_Guidelines. The Google JavaScript Style Guide specifies the following:

  • Declarations of variables always use var, except when intentionally creating a global variable.
  • Always use semicolons. This is important for minifying code.
  • Constants are uppercase, with each word separated by an underscore.
  • Functions, variables, and method names all use camel case notation with the first letter lowercase.
  • Classes and enum names also use camel case notation but with the first letter uppercase.

The big exception to any of these rules is when an example demonstrates how not to do something.

The jQuery team also published a set of conventions for development of the core library. The documentation mentions the following:

  • Spacing code: Abundantly use spacing, using tabs to indent code. Don’t use white spaces at the end of lines and empty lines should not have spaces either. This example illustrates the preferred spacing.

if ( test === “test string” ) {

methodCall( “see”, “our”, “spacing” );

}

  • Using comments: For multiple-line comments use /* */ and for single-line comments use //, with an empty line above the comment. The single-line comment precedes the comment that it refers to, and should be the only thing on the line.

// my comment

var x = ‘blah’;

var x = ‘blah’; // bad

  • Equality: Always use identity (===) comparison over simple quality (==). The jQuery team makes the exception of using simple equality when testing for null. As the guidelines say, “It’s actually quite useful to do == null or != null as it will pass (or fail) if the value is either null or undefined.”
  • Block presentation: Always use braces for control constructs (if/else/for/while/try), and distribute over multiple lines. Don’t use the one liner ifs without braces. Braces should always be placed on the same line as else/else if/catch. It’s also suggested to avoid replacing if/else statements with ternary operators. Here are some examples:

// bad

if( stuffHappens ) alert(‘blaaaah’);

// good

if( stuffHappens ) {

alert(‘blaaaah’);

}

// also good if( option ) {

// code here

} else {

// code here

}

  • Function call format: Include extra spaces around function call arguments with the exception of when a function call is nested, a function call is empty, or object literals and arrays are passed:

// These are OK

f( arg );

f( g(arg) );

f();

f({ });

f([ ]);

  • Arrays and objects: No extra spacing is preferred for empty object and array literals, but do use a space after commas and colons:

var a = {};

var b = [];

var c = [ 1, 2, 3 ];

  • Assigning variables/objects: Always use a semicolon at the end of assignments with an endline afterwards. As noted by the Google Style Guide, semicolons should always be used.
  • Type checks: Table 1-1 demonstrates what strings to use when doing a type check.

Table 1-2 illustrates objects that are type checked using the jQuery API.

Table 1-3 illustrates methods for type checking undefined.

  • RegExp: Create regular expressions (RegExp) with .text() .exec().
  • Strings: Double quotes are preferred to single quotes.

The docs also mention validations with JSLint. JSLint is covered in the next section on Development Tools.

There are differences between the Google JavaScript Style Guide and jQuery’s Style Guide.

For example, the Google JavaScript Style Guide suggests the use of single quotes, whereas the jQuery team uses double quotes as a standard. For this book, we stick to the jQuery team’s suggestion.

Source: Otero Cesar, Rob Larsen (2012), Professional jQuery, John Wiley & Sons, Inc

Leave a Reply

Your email address will not be published. Required fields are marked *