jQuery Introduction

jQuery is insanely powerful so this page won't teach you everything. Hopefully, however, it will give you an understanding of it so that you can read the documentation and have it make sense.

It's that whole "Teach a man to fish" thing.

Useful Resources

Here are some pages you should always keep handy:

  • jQuery API Documentation - This is a great reference once you get the swing of things. This literally contains all of the information about what is available to you in jQuery.
  • W3Schools jQuery Tutorial - I can't say enough about how useful W3Schools site is. It seems everytime I look up something new, I inevitably end up on their site.

Why jQuery?

Vanilla JavaScript can do everything jQuery does so why use jQuery at all? Well, jQuery simplifies and in my opinion makes code cleaner looking. It does come with a little bit of overhead but I don't consider it enough to be concerned about.

jQuery essentially gives you a very clean way of interacting with HTML/DOM, CSS, All sorts of event (click, double click, mouse over, etc.). It also gives you a few utility functions that can make life a bit easier. It has code to help with HTTP request.

Yet another reason jQuery is awesome is that it obfuscates many inconsistencies between browser's JavaScript engines so that you don't have to write special handling for each browser. This is less and less of a problem these days but it still exists and using jQuery means you don't have to worry about it.

Even further, jQuery has additional plugins you can get so you can continue to benefit by other's work instead of reinventing the wheel, no matter how fun that can be.

Finally, the last good reason that jQuery is great is the amount of support behind it. Just to name a few large companies that use it, there are Google, Microsoft, Netflix, IBM. It is a well established technology and there are tons of people working on it to make it better and better which means you have hundreds or thousands of developers working for you that you don't have to pay. Honestly though, if you are in the position to do so, you can probably donate some money somewhere to them.

This all leads me to the reverse question. Why NOT jQuery?

The Parts of jQuery

jQuery gives us access to a few things. It gives us access to the HTML/DOM, aspects about the DOM such as CSS and attributes, Events, and Utilities.

You've Loaded jQuery, Where Is It?

jQuery is loaded into a variable called '$'. Just a dollar sign. In my opinion, this was an extremely bold move on their behalf but it makes it so you don't have to type out 'jQuery' each time you want to use it.

Interacting With The HTML/DOM

Selectors

So you can select objects from the DOM using selectors. These selectors are extremely powerful.

Element Type Selectors

Lets say you want to grab all of the <div></div> elements on a page. That is easy. Just do this:

var allDivs = $('div');

Lets say you want to grab spans, but only ones that are in a div such as: <div><span></span></div> That is also easy. Just do this.

var allDivsWithSpans = $('div span');

So far this is pretty easy, but it is way more bad ass than that. Lets say you have:

<ul>
    <li>0</li>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
</ul>

And you only wanted to grab the odd number rows.

var oddItemsOfList = $('ul li:odd');

There are so many more ways to select via element type but this is only a primer so you can find other ways online. If you want to do it, there is probably a way to do it.

CSS Type Selectors

Lets say you have the following:

<html>
<body>
<div class='green'></div>
<div class='blue'>
    <span class='green'>Blargh</span>
</div>
<div class='yellow'></div>
</body>
</html>

And you wanted to grab all elements that have the 'green' class. You would do:

var greenElements = $('.green');

This would give you the div and the span that have the green class.

Mixing Element and CSS Selectors, we could grab just the div that has the 'green' class.

var greenDivElement = $('div.green');
Attribute Type Selectors

You can also choose items based on attributes such as 'id' or looking for items that have a 'href' attribute.

Example HTML:

<html>
<body>
    <div id='fabulous'>
        <a href='/cowpie.html'>cow pie</a>
        <a href='/goatpie.html'>goat pie</a>
    </div>
</body>
</html>

Lets say we wanted any element with the 'id' of 'fabulous'.

var fabulousDiv = $('#fabulous');

Or perhaps we want items with an 'href' attribute.

var hrefElements = $("[href]");

Or perhaps we want items that have an href that contains the string 'goat'.

var goatHrefElement = $("[href~='goat']");
Other Notable Selector Info

Typically commas are considered 'or' and spaces are considered 'and'. For example:

var elementsWithGreenAndYellowClass      = $('.green .yellow');
var elementsWithEitherGreenOrYellowClass = $('.green,.yellow');

And you can mix and match selector types:

var firstDivElementWithGreenClass = $('div.green:first');

You are mostly limited by your creativity.

Creating Elements

To create elements you can simply pass HTML to jQuery. If you want to make a <div></div>:

var newDiv = $('<div></div>');
// You can also shorthand this xhtml style.
var anotherNewDiv = $('<div />');

Now, these new objects you are creating are somewhere in the twilight zone. They are not attached to your DOM yet and thus are not visible on the page. We will get to that next.

Manipulating The DOM

So lets say we have this example HTML:

<html>
<body>
<div id='content'>
  <div id='subcontent'>
    <span>In subcontent</span>
  </div>
</div>
</body>
</html>

We then create a new div element.

var newDiv = $('<div />');

Again, this div is nowhere on the page or in the DOM. Lets give it an 'id' and attach it to something.

newDiv.attr('id', 'newDiv');
// Now we have the equivalent of <div id='newDiv'></div>
// Lets add some text in it.
newDiv.text('I am the new div.');
// Now lets say we want to append it to the contents of the subcontent div, meaning it will be added
// in right after the <span> tag.
// First we need the subcontent div object.
var subcontentDiv = $('#subcontent');
// Now we append our new div to our subcontent div.
subcontentDiv.append(newDiv);
// At this point our new div is on the DOM and visible on the page.

Now what our page looks like is:

<html>
<body>
<div id='content'>
  <div id='subcontent'>
    <span>In subcontent</span>
    <div id="newDiv">I am the new div.</div>
  </div>
</div>
</body>
</html>

Event handling.

So lets do... something. Again we have the following html:

<html>
<body>
<div id='content'>
  <div id='subcontent'>
    <span>In subcontent</span>
    <div id="newDiv">I am the new div.</div>
  </div>
</div>
</body>
</html>

Every time someone clicks on the newDiv, I want to append another div to subcontent that says 'I am another new div.'.

// Lets get our 'newDiv' by ID.
var newDiv = $('#newDiv');

// Lets add a click handler to our newDiv.
// We do so by calling the 'click' method on our object and passing it a function.
// This function runs every time the event is fired of (every time someone clicks
// the newDiv).
newDiv.click(function() {
  // So anything in here will run when the div is clicked.
  // As before lets grab the subcontent div.
  var subcontentDiv = $('#subcontent');
  // Lets create a new div that has the 'I am another new div.' text in it.
  var anotherNewDiv = $('<div />');
  anotherNewDiv.text('I am another new div.');
  // Then just to show the power of jQuery I will do the same append to subcontentDiv
  // but in this case I'm going to do it from anotherNewDiv's perspective.
  // Prepare for mind blowage.
  anotherNewDiv.appendTo(subcontentDiv);
  // BOOM!!!  <brain material>
});

Each time you click the newDiv another div will pop up below it infinitely until you get bored or you run out of memory 3000 years in the future.

Other Useful Things

Chaining

What is chaining?! This is a little tougher to explain but I'll do my best.

In almost every case, a jQuery object will return itself. So, in relation to my other pages, it will return its own 'this' or 'self'.

What this does is it allows us to chain commands together. Lets say I want to make a div, give it an id, give it a class, and give it some text.

var newDiv = $('<div />').addClass('creamy').attr('id', 'newDiv').text('This is an awesome chain.');

What happens is this... The interpreter executes from left to right.

var newDiv = $('<div />').addClass('creamy').attr('id', 'newDiv').text('This is an awesome chain.');

// First we do $('<div />') which returns a jQuery Object.  Gonna call this jQueryObj for explanation
// sake.

// Next, the command would look like this.
var newDiv = jQueryObj.addClass('creamy').attr('id', 'newDiv').text('This is an awesome chain.');
// It adds the class 'creamy' and returns itself.  So next we would have:
var newDiv = jQueryObj.attr('id', 'newDiv').text('This is an awesome chain.');
// It then adds the id of newDiv and once again returns itself.
var newDiv = jQueryObj.text('This is an awesome chain.');
// It then adds the text and returns itself.
var newDiv = jQueryObj;
// And now newDiv equals the jQueryObj that has all of those attributes.

Chaining is very handy when you want to do a ton of things. It also makes it easier to write because you can format it like this:

var newDiv = $('<div />')
             .addClass('creamy')
             .attr('id', 'newDiv')
             .text('This is an awesome chain.');

Don't assume because jQuery allows chaining that other libraries will allow chaining. The library has to be specially designed to allow chaining. Thankfully jQuery is.

Utilities

A good reference here is W3School jQuery Misc Reference.

The one I really want to point out is 'data'.

var newDiv = $('<div />');

newDiv.data({
  'what_is_this':       "This is a nice way to store metadata about an object.",
  'where_is_it_stored': "This is not in the DOM, this is special jQuery in-memory metadata.",
});

// Later on that page you can recall the data.

console.log(newDiv.data().what_is_this)
// Outputs: "This is a nice way to store metadata about an object."

Summary

jQuery is freakin' awesome. I only scratched the tiniest surface of what it can do. Hopefully this gets you to the point where you have enough understanding that you can continue teaching yourself.

I find the toughest hurdle is getting the basic understanding of something but once that clicks it is easy to learn the rest.

Best of luck to you!