Introduction to jQuery Basics

What jQuery is how to get started with the most popular JavaScript library on the web.

Scroll down...

Content

Resources

Comments

Now that you've had a chance to play with JavaScript, let's add a little more firepower to your toolbox. jQuery is JavaScript's most popular and useful library.

You can do pretty much anything with JavaScript -- you can move elements around on the page, alter CSS, tweak the DOM, etc. You're really only limited by your creativity and time. Yes, time... that's the problem. You could write a JavaScript function to animate a dropdown or send AJAX requests, but why?

jQuery saves you a significant amount of time and greatly expands the kinds of things you can do with your browser. More than that, it deals with all the painful annoyances of making sure things are cross-browser compatible. It's a full-featured set of finders, animations, convenience functions and even utility functions that will quickly become indispensable to your workflow.

In this lesson, we'll take a brief look at what jQuery is and how it can help you. The upcoming lessons will dive deeper into its syntax and the application thereof.

Including jQuery

jQuery is an independent JavaScript library that gives you all kinds of useful functionality while removing the dirty implementation details and ensuring cross-browser compliance.

Because jQuery is a JS library, you'll need to include it in your project. The typical way of doing this is by either serving it directly from your project or grabbing it from a CDN on the web.

Visit their download page for more info, but an example of their CDN link is:

<html>
  <head>
    <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
    ...
  </head>
  ...
</html>

How to include it is up to you. Because the library is sent to the browser with each request, it's important to at least think about the performance impact of transferring that much data constantly.

You can download either the uncompressed (human readable) or compressed (minified) versions. Just make sure your app eventually compresses and minifies it before sending to the browser if you do opt for the uncompressed version.

As a final note, there are additional libraries which provide even more functionality on top of jQuery. This includes jQuery UI, a library of user interactions and interfaces which are built on top of jQuery, and jQuery Mobile, a mobile-optimized package of interactions. Despite their names, they are separate (and non-essential) libraries. Including them in your application will add additional overhead, so just make sure you actually need them if you choose to follow some web tutorial that recommends using them.

The Very Basics

To get your feet wet:

  1. Read this very brief mini-tutorial from learn.jquery.com. Note that it covers callbacks, which we'll get to in a later section.

All the top-level functions of jQuery are neatly namespaced beneath the jQuery function. Or is it an object..? Like so many other things in JavaScript, it is a function and, therefore, also an object. You can call it like a function, e.g. jQuery("#some-id"), or access the methods that have been attached to it like an object, e.g. jQuery.ajax(...).

In practical usage, the jQuery function has a very specific meaning -- it finds a selector or group of selectors on the page and returns them wrapped inside a special "jQuery object". Yes, there is the jQuery function which returns a "jQuery object" and, yes, it's sometimes confusing which one you're referring to. We'll talk about this returned "jQuery object" shortly. For now, think of it as an array.

jQuery(...) is really just a shortcut wrapper for JavaScript's findElementById(...), findElementByClass(...) etc. functions. Pass it a CSS-like selector and it will return everything that matches. Some examples (run on the jQuery docs homepage):

// find the selector with ID of `post-5`
jQuery("#post-5");
//=> [<article id=​"post-5" class=​"post-5 post type-post status-publish format-standard hentry category-miscellaneous-traversal category-10 category-14">​…​</article>​]

jQuery(".category-miscellaneous-traversal");
//=> [<article id=​"post-5" class=​"post-5 post type-post status-publish format-standard hentry category-miscellaneous-traversal category-10 category-14">​…​</article>​,
<article id=​"post-7" class=​"post-7 post type-post status-publish format-standard hentry category-miscellaneous-traversal category-18">​…​</article>​,
<article id=​"post-27" class=​"post-27 post type-post status-publish format-standard hentry category-deprecated-18 category-miscellaneous-traversal category-12">​…​</article>​,
<article id=​"post-105" class=​"post-105 post type-post status-publish format-standard hentry category-miscellaneous-traversal category-12">​…​</article>​,
<article id=​"post-171" class=​"post-171 post type-post status-publish format-standard hentry category-miscellaneous-traversal category-10">​…​</article>​,
<article id=​"post-449" class=​"post-449 post type-post status-publish format-standard hentry category-filtering category-miscellaneous-traversal category-10 category-14">​…​</article>​]

The jQuery Object

The "jQuery object" returned by the jQuery function isn't just an array-like wrapper for DOM elements. It also contains a litany of useful helper methods which can be called dot-style, for instance:

// add a specific class to each item that was returned
// look waaaay off to the right and it's on there!
var myJQueryObject = jQuery("#post-5");
myJQueryObject.addClass("my-fake-class");
//=> [<article id=​"post-5" class=​"post-5 post type-post status-publish format-standard hentry category-miscellaneous-traversal category-10 category-14 my-fake-class">​…​</article>​]

If jQuery can't find anything that matches your criteria, it just returns a blank jQuery object (so it doesn't break any other functions that are chained to it):

// Finding something
jQuery(".page-header")
//=> [<div class=​"page-header">​…​</div>​<h1>​jQuery Basics​</h1>​</div>​]

// Finding nothing
// That isn't *actually* an empty array...
jQuery()
//=> []

The many functions provided by the jQuery object are listed in the docs, and we'll cover them over the upcoming lessons. These functions are the true power of jQuery.

The $ Shortcut

Because it's a pain to write out all 6 letters of jQuery, the developers of jQuery decided to alias it as the single $ character. That's a valid variable name so they took it. Now, instead of typing out jQuery(...), you can just write $(...) and it means the same thing. This is used everywhere.

This is the last time you'll see us use jQuery as a function... from now on, we'll use the conventional $ notation.

The jQuery Function is Not the jQuery Object

As a further clarification of what we said above -- the top-level "jQuery function" $ is not the same thing as the object it returns, which is the "jQuery object". $ is just the search function (plus some utility methods).

The "jQuery object" returned by $, which usually represents a collection of DOM elements that jQuery was able to locate for you, has its own special powers. In fact, most of the methods you'll run in jQuery (for instance iterating over that collection of DOM elements and giving each one a new property) will be run on one of these jQuery objects. This will become clearer over time.

To learn more about the distinction between these two, see this article from learn.jquery.com.

When To Run jQuery

As you should recall from our earlier look at running scripts in the browser, your browser runs through the HTML you've provided and uses it to build the full DOM tree of objects. If you try to run a script somewhere in the middle, it may attempt to modify something that hasn't yet been added to the DOM. This is a common problem.

The ideal situation is to ensure that the page is finished loading before running your script(s). The old way was to simply put your <script> tags at the end of your <body> tag in the DOM. Lucky for you, the browser provides a notification when it has reached the "document ready" stage. jQuery gives you a simple function called ready which you can pass anything that needs to wait for the browser to finish loading.

In practice, you will pass all your scripts into a ready function, wrapping them in an anonymous function so they don't immediately get executed:

// a simple log wrapped in an anonymous function
// which is defined (but not run yet) right there
$(document).ready( function(){ console.log("done!") } );

// pass a named function wrapped in the anonymous one
$(document).ready( function(){ runMeLater() } );

// Using an anonymous function to wrap all
// the other functions you really want to run.
// It runs as soon as the document is finished
// and so all the internal functions do too.
$(document).ready( function(){
  theFunctionYouReallyWantToRun();
  anotherFunctionYouLike();
})

You don't even technically need to pass in the document object, e.g. by using $().ready( ... ), but it's conventional to do so. It's better to know for sure that this will be document instead of leaving it unspecified and having it default to the global Window object.

Mastering your Dev Tools

As we get into the real browser work, it's worth verifying that you're up to speed with your developer tools. If you thought you and the dev tools got well acquainted as part of the HTML course, you're going to really get familiar with them while trying to debug JavaScript.

The quick video 12 Tricks to Develop Quicker from Chrome Developer Tools provides a useful look at debugging with the dev tools. This includes tips like inserting log statements directly in the console and pausing execution of JavaScript code on errors.

Code Review

The important bits of code from this lesson

// Include jQuery via CDN
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

// Grab an element by its selector
jQuery("#post-5");

// Use the MUCH more common $ alias for `jQuery`
$("#post-5");

// Wait until the document is loaded to run
$(document).ready( function(){ console.log("done!") } );

Wrapping Up

By now you've gotten a sufficient taste of jQuery to start digging deeper. Over the upcoming lessons, we'll show you how to unlock the $ function's selection capability to retrieve elements from the page and then how to take advantage of the methods provided by the jQuery object it returns to add, remove, alter, or animate to your heart's content.



Sign up to track your progress for free

There are ( ) additional resources for this lesson. Check them out!

Sorry, comments aren't active just yet!

Next Lesson: Taking JavaScript to the Browser