Getting Started with jQuery

The web development scene is moving forward at a lightning-fast pace, and it’s imperative that developers continue to keep their skills fresh. If you’ve been involved in front-end design or development in any form over the past five years or so, then it’s very likely that you’ve experimented at some point with one of the popular JavaScript libraries, many of which have become quite prominent and are now used on a number of large commercial websites.

Getting Started with jQuery

In this article, I’ll be introducing and laying the groundwork for advanced JavaScript development with one of the most popular JavaScript libraries available: jQuery.

Although there are many beginning tutorials online that can provide a great starting point for jQuery development, in this article I’m hoping to go beyond just quick-start syntax and instead provide a solid overview of jQuery and discuss the benefits of using such a library. Of course, much of this information–outside of the syntax and other jQuery-specific details–will be applicable to any JavaScript library.

Why a JavaScript library?

To quote the official jQuery slogan: “Write less, do more.” The role of a web developer is to create code that determines what will result from a user’s interaction with a web page. Web developers should not have to spend hours debugging browser quirks. Instead, they should be free to deal solely with the actions and the results. This is where a JavaScript library comes into play.

Overcoming browser differences

Different browsers handle DOM manipulation, transparency effects, and animation in different ways, requiring, in some cases, reams of code just to create a simple effect. Using a JavaScript library allows you to completely bypass all of those challenges, giving you access to an API (Application Programming Interface) that deals directly with the tasks you actually want to accomplish. All the challenges and issues common to JavaScript are dealt with behind the scenes, allowing you to integrate functionality without wondering whether or not it will work in a particular browser.

Unobtrusive JavaScript

Another impelling reason to use a JavaScript library is that all libraries allow you to include JavaScript in your pages unobtrusively, thus keeping your behavior layer (the JavaScript) separate from the content and presentation layers (the XHTML and CSS).

Accomplishing complex tasks with ease

Finally, a very powerful feature of any JavaScript library is its ability to manipulate any element or set of elements on a web page with just one line of code. Take, for example, the following HTML:

<div>
  <ul>
    <li>Text Here</li>
    <li>Text Here</li>
    <li>Text Here</li>
    <li>Text Here</li>
    <li>Text Here</li>
  </ul>
</div>

Let’s say you wanted to use JavaScript to change the background color of the first list item element (<li>) in the unordered list above. Using pure JavaScript, your code would look something like this:

var myListCollection = document.getElementsByTagName("ul");
  for (var i = 0; i < myListCollection.length; i++) {
    if (myListCollection[i].className === "list") {
      myListCollection[i].childNodes[0].style.backgroundColor = "blue";
    }
  }

Using jQuery, you can accomplish the same thing with just one, easy-to-maintain line of code:

$("ul.list li:first-child").css("background-color, "blue");

Further reading

Understand CSS concepts

One area that is imperative to powerful jQuery development, is strong knowledge of CSS. The reason for this is because jQuery often utilizes CSS-based syntax to manipulate DOM elements. Here are some concepts that you should be quite familiar with before diving into extensive jQuery development:

  • Type selectors
  • Class selectors
  • ID selectors
  • Descendant Selectors
  • Child Selectors
  • Attribute Selectors
  • CSS Specificity
  • The Cascade & Inheritance

Most of the above CSS concepts should already be very familiar to any modern-day front-end developer, since any CSS layout would utilize these. jQuery not only incorporates the basic selectors (type, class, and ID), but it also uses descendant and child selectors, which aren’t supported by all currently-used browsers. But with jQuery, due to its built-in browser normalization, all selectors are supported equally.

Understanding that jQuery incorporates CSS syntax when accessing elements will greatly enhance your ability to quickly and easily create powerful JavaScript applications with jQuery.

Understand JavaScript concepts

In order to make full use of jQuery, it is a good idea to learn certain JavaScript concepts. Sure, you can do a ton of stuff in jQuery without knowing much about some of the concepts listed below, but you’ll have a bigger advantage in your jQuery development if you take the time to understand a few fundamentals, including:

  • Object creation
  • Properties of objects
  • Object literals
  • Functions as methods
  • Anonymous functions
  • Closures

Again, it is not necessary to fully understand any of the above concepts in order to start working with jQuery, but your abilities with jQuery’s API will increase greatly if you understand one or more of the above concepts.

The jQuery source code

Before getting started with any jQuery development, you’ll first have to download the latest version of the jQuery library and include it in your pages:

<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>

The above line of HTML should appear before any actual jQuery code, otherwise you’ll get errors.

Alternatively, instead of hosting the source code yourself, you could link directly to the most recent version on the Google Ajax Libraries API which can save you some server resources. (read more ways to offload website features).

jQuery syntax

Now that you have an overview of the benefits of jQuery, along with some understanding of concepts involved, let’s take a look at some syntax to get us started with this powerful library.

The jQuery wrapper

The jQuery wrapper is the function that is at the core of all jQuery commands. I used it earlier in one of the examples above. Here it is again:

$("li a");

The $ symbol is an alias for the jQuery function, so the above line of code could alternatively be written:

jQuery("li a");

But, for obvious reasons (e.g. to keep your code terse), you’ll rarely see that syntax.

The jQuery function shown in the above two examples returns an object containing an array of the DOM elements specified inside the parentheses (in this case, all anchor tags that are nested inside of <li> tags). Of course, in both examples above, we haven’t specified an action; all we’re doing is returning those DOM elements, which does nothing. In the next section, we’ll add methods that will act on the group of elements we’re targeting.

jQuery commands

jQuery’s API includes easy access to effects and other actions via built-in methods that would normally take dozens of lines of code to accomplish in a cross-browser fashion with pure JavaScript. For example, let’s add a “fade out” method to the code from the previous examples:

$("li a").fadeOut();

The above line of code “fades out” all anchor tags on the page that are nested inside of <li> tags. If we want to fade the anchors back in again, we just use the fadeIn()method:

$("li a").fadeIn();

Chaining commands

jQuery also allows developers to chain commands, stringing one after another. So, we could combine the previous two examples, as follows:

$("li a").fadeOut().fadeIn();

The above code will fade out all anchor tags nested within list items, then immediately fade them back in. The number of chained items is infinite (or within reasonably set limits), allowing for numerous commands to work on the same group of elements, each happening in succession.

That’s just a small sampling of what’s possible with jQuery, and how easy it is to accomplish tasks that would normally take many lines of code, and a lot of browser testing. Although you’ll still do browser testing when running jQuery code, the results will virtually always be the same: cross-browser, unobtrusive JavaScript that’s easy to write and easy to maintain.

Running code when the DOM is ready

Earlier we touched on the concept of unobtrusive JavaScript, and how jQuery is written to allow your scripts to remain separate from content and presentation. So far, the code examples we’ve discussed would run fine as long as they were included at the bottom of an HTML page. If, on the other hand, they were included in the head of the document, they would fail to work because, at that point, the document tree has not yet rendered.

jQuery allows us to run our code only when the DOM is ready. This is done by means of the $(document).ready handler. The beauty of this handler is that it doesn’t make the code wait until the entire page finishes loading, as would be the case with a typical window.onload event. With the (document).ready handler, your code will run as soon as the DOM tree is finished rendering, before all images and other media have finished loading, thus minimizing load time.

Let’s try running our previous code example when the DOM is ready:

$(document).ready(function(){
  $("li a").fadeOut().fadeIn();
});

The above code tells jQuery to run an anonymous function when the document tree is done rendering. The anonymous function contains the code we saw previously, which faded our anchors out, then immediately faded them back in again. This code could be included in the <head> of the document, near the bottom of the page, or anywhere else, and it would run exactly the same way.

The “ready” event is just one of the many events available through jQuery’s API. Others include clickdblclickloadblurkeydownsubmit, and more.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: