Skip to Main Content

jQuery, and all related tutorials and information will be found here...

Chapter 1 - jQuery 101

CHAPTER 1

jQuery 101

Understanding the basics of jQuery

Surrounding the web development and web design industry is a constant need to be on the "cutting edge" of functionality and user interface design. Without the ability to learn new methods quickly and implement them appropriately, a web industry professional can quickly fall behind the curve. jQuery is quickly becoming one of the most powerful sets of tools you can use as a web developer to enhance the core interface design of your projects, and keep your clients coming back for more.

Through the power of jQuery, we will examine various ways to enhance your current projects quickly and easily. Many of the examples throughout this book are simple one, two, or three line snippets of jQuery code that add some very interactive features to otherwise dull elements on page. After learning some of the basics of jQuery highlighted here in the first section, you will be ready to jump from example to implementation in no time at all.

Introduction - What is jQuery?

jQuery is a fast, concise, JavaScript Library that simplifies how you traverse HTML documents, handle events, perform animations, and add Ajax interactions to your web pages. jQuery is designed to change the way you write JavaScript. --jQuery.com

This short and simple description found on the jQuery home page describes the jQuery library in a way much like the code behind the jQuery project, straight to the point. The jQuery library was originally created by John Resig, but is now backed by a team of developers and a large community that contributes to jQuery by creating plug-ins that extends the functionality of the jQuery core.

jQuery is a JavaScript Library, or a collection of pre-built JavaScript functions that provide certain types of interactions with elements in your pages. By including the jQuery source code in your document, you are then able to reference the functions built into the library in your code by simply calling a function and supplying a few simple parameters.

How jQuery is effective

What makes jQuery useable in so many situations is how quickly you can manipulate a large portion of a page or website by just adding a few simple lines of jQuery to your code. By applying jQuery code to a certain class or element on page, you can modify a complex site using an advanced content management system that has its own unique way of creating the layout and code without actually touching the source code of that project. In my experience with jQuery, it has allowed my projects, old and new alike to receive new life, and interactivity with little effort. jQuery provides an easy to understand syntax in referencing page elements by CSS attributes.

Common misconceptions

Most programmers and designers who aren’t fluent in JavaScript quickly cringe at the thought of anything dealing with writing JavaScript. I used to be the same way myself. However, with the creation of jQuery, a designer/developer with little or no JavaScript knowledge can easily create advanced user interfaces without worrying about the complexities of programming confusing DOM JavaScript.

Chainability

jQuery uses chainability to shorten lengthy operations on a single or multiple objects into a single line of code, and helps eliminate the need for many looping constructs to traverse over a set of results that you see in a lot of coding. Chaining commands essentially means that you can perform multiple commands on an object in order without having to declare the item you are operating on again.

Listing 1-1. Chainability at use

$(“div”).fadeOut(“slow”).fadeIn(“fast”).fadeOut(“fast”).fadeIn(“normal”);

The code above would operate on any <div> element, and first fade out each <div> element slowly, then fade in the element quickly, fade it back out quickly as well, and lastly fade it back in at a normal pace.

Without chainability, the same four commands would have been written like this using callbacks.

$(“div”).fadeOut(“slow”, function(){
$(“div”).fadeIn(“fast”, function(){
$(“div”).fadeOut(“fast”, function() {
$(“div”).fadeIn(“normal”);
});
});
});

The benefit of using the chaining method in terms of code brevity is apparent, but can quickly become hard to decipher by someone other than yourself so you can properly use the chaining method, including very good commenting by rewriting the first example like this.

$(“div”) // item to operate on
.fadeOut(“slow”) // first fade out slowly
.fadeIn(“fast”) // fade back in fast
.fadeOut(“fast”) // fade back out fast
.fadeIn(“normal”) // fade back in at an average speed
; // end

Callbacks

Another magical feature in jQuery is the ability to assign callbacks to many of the built in functions. A callback is executable code, in this case a function that is passed as an argument to the function being called. This allows the function that was called to perform its operations, and then fire the callback function we passed as a parameter at the end. The following code demonstrates callbacks from the section above.

$(“div”).fadeOut(“slow”, function(){
$(“div”).fadeIn(“fast”, function(){
$(“div”).fadeOut(“fast”, function() {
$(“div”).fadeIn(“normal”, function(){
// and additional functionality placed here inside of final callback
}); // end of final fade in
}); // end of final fade out
}); // end of first fade in
}); // end of first fade out

You can see that inside our original fadeIn and fadeOut functions, we have inserted a function as the second parameter, which will be used as our callback function. It’s most interesting to see how deeply nested this can become with each callback function calling another function with yet another function as its callback.

Launching code using $(document).ready();

Many times in the implementation of JavaScript code, there are functions you would like to execute after the completion of the page load. This can either be a function that provides a simple alert message, modifies the DOM in some way, or provides some custom functionality you’ve coded. You can find many older JavaScript functions that require you to modify the <body> tag in order to make a call to this function after the page has finished loading, or they might use the window.onload event to accomplish this effect as well.

So in order to implement a function named JavaScriptFunction() on page load, you would have to had used a method similar to one of the following examples.

Listing 1-2. Using onLoad event

<body onLoad="JavaScriptFunction();">

Listing 1-3. Using window.onload event

window.onload = function () {
JavaScriptFunction();
}

Both of the methods above are not a proper way to implement this onload event with any type of flexibility for proper browser compatibility and timing. The window.onload function can accidentally be overwritten by another function or included JavaScript file, and the body onLoad method can quickly clutter up your clean XHTML format with code that should be included separately, along with also causing unexpected errors when including other JavaScript codes. Both methods above also do not execute until the page is fully loaded, and in this case, that includes images finished downloading. Essentially, the usage of the above formats can cause unexpected issues without the proper knowledge of all the JavaScript functionality that occurs in your document.

jQuery provides a simple and very effective way to accomplish this same effect. The ready() function, which can be used multiple times in a single file or page will call the appropriate function assigned as a callback to be executed once the page is fully inserted into the DOM. One benefit to this is that your code can easily be included in any area of your document including the header, footer, included via a remote JavaScript file, or inline with other XHTML in your page, and it will be read, and executed appropriately once all the elements of the page have been traversed by the DOM. In this situation, the DOM being loaded does not include images being fully downloaded, so scripts can start earlier.

Listing 1-4. Using the jQuery $(document).ready(); function

$(document).ready(function () {
JavaScriptFunction();
/* Many other functions can be called here */
});

Inside this construct you can provide your own custom JavaScript function such as the one listed, or call other jQuery functions that have their own purpose and callbacks to other functionality as well. Using the $(document).ready(); function allows you to simply be sure that your functions aren’t being called on an object that has not yet been loaded, which would cause the function to either fail, or simply be skipped over.

Adding simple jQuery functionality to your document

With a few of the examples above illustrating chainability and callbacks, you’ve seen some basic jQuery code, but not a proper context in which to place that code, so we’ll begin now by getting ready to start using jQuery in your project.

Downloading jQuery

You can always download the latest version of jQuery at the official jQuery site. (jquery.com) At the time of this writing the current version is jQuery 1.2.6.

Figure 1-1. jQuery homepage download options

Downloading jQuery

You will notice several different options here to choose from. Each has its own purpose, and you should have a general understanding of each to get the appropriate version for your project.

  • Minified and Gzipped version. This version will be used for production on most sites and web servers. It minifies the jQuery code, removing line breaks, white space, and other unnecessary items, then uses compression to make the library as small and fast as possible. Currently 15kb
  • Uncompressed version. This version will work best for advanced developers that want to investigate how jQuery operates, and how each of the built in functions break apart. It is fully commented as the original and great for reference when building custom plug-ins and advanced jQuery functionality. However, due to the large file size at almost 100kb, it is not recommended to use on a live site as it could slow down load times. Currently 97kb
  • Packed version. The packed version is the same as the Minified version, except the code is not compressed using the gzip method. Some web servers will not be able to handle the compressed version, and will require using this larger 30kb, packed version instead for production sites. Currently 30kb

For all of my projects, I use the minified and gzipped version to include in the actual document, and also keep a copy of the uncompressed version for quick reference when needed. Depending on your need to further understand the underlying code, you may or may not want to keep the uncompressed version around.

Including jQuery in your document

Now that you have downloaded jQuery, you can include it into your document easily by using the standard method of including any JavaScript document. This should be placed between the <head> and </head> tags on any page you wish to include jQuery, or in a header file that is repeated throughout your project to ensure its automatically included on each page.

Or you may want to use the file for local development and testing, and include it using relative paths so that your local system can properly determine the location.

Integrating jQuery in your code

Now that you have jQuery downloaded, and the core jQuery file being included in the header of our document, you are ready to start calling jQuery functions on elements on your page. So far through some definitions and explanations of how jQuery works, you’ve seen a few examples of jQuery code, but now we’ll move into understanding how to integrate that code into something useful in your document. The following examples will give a simple line of jQuery code that would serve a valid purpose in many situations, along with a description of what it accomplishes, and breaks down how it’s done.

The problem with target="_blank"

As of XHTML 1.0 Strict, and XHTML 1.1, the target attribute for href links is no longer valid, and will throw validation errors if you continue to use it in your code. The following example provides an easy method to correct this issue.

This first example simply removes the need for target=”_blank” in the original code, and inserts the parameter using jQuery to insert into the DOM which will not interfere with a proper validation.

Listing 1-5. The original href with improper usage for XHTML 1.0 Strict

<a href=”http://himerusinc.com/” target=”_blank”>link text</a>

Listing 1-6. The new href with proper usage for all XHTML versions

<a href=”http://himerusinc.com/” class=”external”>link text</a>

What you can see here is only a simple change, easily removing the outdated target attribute, and replacing it with a class attribute that we may use jQuery to operate on. What this does is take all of the links we want to open in a new window, and format them appropriately for the XHTML validator so that the page may still pass validation and applies a class that we can refer to using jQuery to still have these flagged as the appropriate links to open externally.

Now we can apply this simple line of jQuery that will, once the page is fully loaded in the DOM, add the target=”_blank” parameter back to those links that we’ve named with the external class.

Listing 1-7. Simple jQuery snippet to add attribute to links with the “external” class.

$(‘a.external’).attr(‘target’,’_blank’);

This code tells jQuery to first search for any <a> tag with the class attribute external assigned to it. Once it has found all of those matching items, then it uses the attr() function to assign a new attribute to those links returned as an object by jQuery. The attr() function takes two parameters, the first being the actual named attribute. In this case, target and assigns it the value of the second parameter, in this case, _blank.

By using this example, we’ve corrected an issue that would prevent our document from validating XHTML properly, but have then went ahead, and reapplied the functionality that we are used to so that those links could still open in a new window. The issue with this is that some browsers in the near future will likely not recognize the target attribute all together, which would render the simple one line method useless. A more proper way to accomplish that should work well into the future would be the following.

Listing 1-8. Proper usage to open new window using jQuery.

$(‘a.external’).click(function(){
window.open($(this).attr(‘href’));
return false;
});

This example uses a method that will work for any browser that has JavaScript enabled, and will not have issue in a browser that no longer recognizes the target attribute. We have taken the same initial starting point for the jQuery request, calling for any <a> tag that has a class of external associated with it, and now we are assigning a function to the click event. Inside that click function, we quickly call the window.open function with another jQuery function as its parameter. Using the $(this) selector, we are referring to the item that was clicked on, and not any other links with the same class. In this example, we are again using the attr() function, but only passing a single parameter which is the attribute we are looking for, which in this case is the href attribute. We finally use return false; to ensure the main browser window stops executing, and does not link to the linked page as well as opening it in the new window.

Both examples here show usage of the attr() function, and the second, including the click() function as well. The attr() function, when using two parameters, assigns a value in the second parameter to the attribute assigned as the first parameter. If we use the same function, but only use the single parameter as in the second example, it requests the value of that attribute you’ve designated as the parameter.

Cleaning up links that use javascript: void(0);

I enjoy keeping my base XHTML code as clean and uncluttered as possible at all times. Using the same methods as above, there are a lot of times I want a link to simply activate a jQuery function, while doing nothing else. Using the class selectors like above searching for the external class is an easy way to find the links you want to operate on in most cases. In a lot of older code, I found myself always using the javascript: void(0); function as the href attribute in order to cancel the click on the link, and not forward to another page. However, if you were using this type of modification in a lot of links on page, you can quickly have a lot of ugly code in your main document.

I choose now to simply replace those same href attributes with a simple pound sign (#) instead, and use jQuery on the backend to handle the click function.

Listing 1-9. The original link

<a href=”javascript: void(0);”>link text</a>

Listing 1-10. The new link

<a href=”#”>link text</a>

Now you can see how much space this saves in your XHTML documents, and for no other reason besides the abbreviated code, and cleanliness of the source code, you can apply the following jQuery to accomplish the same thing.

Listing 1-11. The new link

$(‘a[href=#]’).attr(‘href’, ‘javascript:void(0);’);

This quickly updates all of those links with “#” as the href attribute, and replaces that attribute with javascript:void(0);. We can again, accomplish this in a more flexible way for further jQuery functionality to be applied easily later by using something more like this.

Listing 1-12. Proper usage for new link.

$(‘a[href=#]’).click(function(){return false;});

This last example will not change the actual value of the href attribute, but only apply the same effect as using javascript:void(0); to any link that has a # as the value of the href attribute. So we could further expand this later by using this as somewhat of a default for any link using the # as the href value, and then apply other click functions via the class identifiers. Doing it this way, in those subsequent functions would eliminate the need to include the return false; call in each click function we create.

Importance of valid XHTML

With jQuery, the importance of proper XHTML is immense. When using DOM based references, the JavaScript engine in your browser depends on being able to properly understand the layout of your page, and the elements it contains. All tags should be properly closed and nested appropriately, otherwise, when attempting to reference an element on page you may receive unexpected results.

Most modern day browsers attempt in some way to correct these issues automatically, but depending on the situation, may not do so in the way you intended, and render the functionality useless, or completely break down the layout and organization of the code on page. I can’t stress enough how important it is to ensure your XHTML code is 100% valid as you implement DOM based JavaScript, in this case jQuery code. Learning how to easily code valid XHTML will save time not only in situations with jQuery involved, but in layout debugging, and browser compatibility. Many a headache in the development process can be diverted by simply ensuring your base XHTML code is put together appropriately as defined by the DOCTYPE assigned to your page.

Conclusion

In this first chapter, I’ve introduced some of the basic ideas behind jQuery and getting started using it in your projects. This section is really meant to just touch on the concepts for new users to jQuery, and provide a quick reference for the basics of setting up jQuery in your document, and starting to implement basic functionality along with understanding how jQuery is used including a couple of practical examples of using it.

As we move into the next chapters, you will explore some of the more advanced functionality, and how to further improve your projects using the jQuery JavaScript library. By this point, you should be ready to move on, already have jQuery included in your pages, and have the ability to continue expanding the usability of any interfaces you are creating by adding simple jQuery functions to page elements.

My Latest Tweets

  • Please wait while my tweets are loading, or if there's an issue, just go to my twitter page.