UX Design and Development course

Intro exercises to jQuery

There are two ways to load jQuery into your app. At the head and at the end of the </body> tag. It is highly recommended that you load jQuery at the end of the document as this reduces opportunity for conflict with DOM loading and adds to the perception of speed.

Where you load jQuery has an impact on how you need to structure your code. Most tutorials use this $(document).ready function as it is most common to place the JavaScript in the <head> tag.

When you load it in the head, you need to wrap all your jQuery in the following syntax:

$(document).ready(function() {
    // code goes here
});

The reason for this is that jQuery, or most JavaScript in general, requires that the DOM be loaded before any actions can happen. Basically, when the "document is ready" then you can run your scripts.

If you load jQuery at the end of the document, this wrapping anonymous functions is not needed.

What is the DOM?

A tree-like structure that allows technologies like JS and jQuery to easily interact with the presentation in the browser.

The HTML from your web page, as loaded into the Browser, each HTML element and the content within crates what are called 'nodes in the DOM'. The following is an example of some simple HTML you would have in a page:

<!DOCTYPE HTML>
<html>
<head>
    <title>This is a title</title>
</head>
<body>
    <h1>This is a header</h1>
    <p>This is some text</p>
</body>
</html>

The rendered DOM tree of nodes may look something like this: (Remember, all nodes are children of the Document Object)

|- Document
|--- HTML
|----- Head
|------- Title
|--------- "This is a title"
|--- Body
|----- h1
|------- "This is a header"
|----- P
|------- "This is some text"

All browsers use Javascript to interact with the DOM.

Why jQuery and not just Javascript?

Truth be told, you can simply use JavaScript, and my developers denounce the use of jQuery. What it boils down to is, if you are not using jQuery, then you are building a library like jQuery and chances are that it will not be as robust as jQuery and is all the additional time, effort and resources worth saving 4k of bandwidth?

Not to mention, the team behind jQuery are extremely knowledgeable of the differences between each browser DOM interface. Are you?

What is jQuery

An abstraction JavaScript library with a pre-developed API. jQuery makes it easy to do:

  1. Find elements in the DOM
  2. Change HTML content
  3. Listen to what the user is doing for an interactive experience
  4. Animation
  5. Make asynchronous network calls (AJAX)

Basic jQuery usage

Open the browser and the Inspector.

To write a basic jQuery statement

jQuery(<code>).method(function();

Developers are lazy, built into jQuery is an alias. Instead of jQuery, you will use $

$(<code>).method(function();

jQuery makes of use CSS selectors to access DOM elements. These are called 'jQuery Selectors'. For example, if you needed to find all the h1 selectors in the DOM, you would write:

$("h1");

Notice how the h1 is written with double quotes, " ". Document selectors are passed into the jQuery statement as 'strings'.

jQuery standard syntax

When you call the $() function and pass a selector to it, you create a new jQuery object.

$("some-DOM-object").method(function() {
    // code goes here always with a training semi-colon;
});

Find and modify

Protip: For these examples, find any website that may contain an h1 element and open the Chrome Inspector. In the inspector, select the 'Console'.

Now that we know how to find an element in the DOM, how do we modify it? To do this, jQuery makes use of what are called 'methods'. jQuery Methods are pre-written features of the jQuery language that you can access via the API.

For example, say that we want to get the text of an h1 element within the DOM. To do this, we can make use of the text() method like so:

$("h1").text();

Using this, we can modify the text. Just need to pass the new string into the text() method, like so:

$("h1").text("I ROCK at jQuery!");

This is pretty fun, let's look at more examples we can do in the browser. There is a good chance that the website you are looking at has multiple <p> elements. If were to enter the following statement into the Console, this would select and report all the <p> element nodes in the DOM.

$("p");

To really screw things up, use jQuery to replace all the text in the page:

$("p").text("I am the master of the Grid!");

Ok, this is pretty brute force. How can we be more selective? In jQuery, just like CSS, you can select DOM elements by classes, IDs and attributes.

Open the Inspector on any given website and find an element with a class, ID or attribute. For example, go to this Github repo and target the a tag with the attribute of itemscope and change the text like so.

$("a[itemscope=url]").text("these are new words");

Since we are there, let's do some more interesting things like adding CSS classes.

$("a[itemscope=url]").text("these are new words").addClass("foo");

This is a static application of this method, but later on we will talk about how you can bind this to click events to add, remove and toggle CSS classes on the DOM tree.

To all the CSS purists out there, the following is the grossest thing you can do, but in some cases it is necessary. Adding inline style CSS. Using the css() method, you can pass in two objects, one for the property and the other for the value, like so:

$("a[itemscope=url]").text("these are new words").css("color", "orange");

Use this with reservation!

Using jQuery

Playing with jQuery in the browser is pretty fun, but how do you get jQuery to run in your project? Simple, add it to your HTML files. Always keep tabs on HTML5 Boilerplate as this keeps up with best practices.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.0.min.js"><\/script>')</script>

Searching the DOM (traversing with CSS selectors)

The key to understanding how to search the DOM in jQuery, you simply need to understand the rules that govern how to select DOM elements with CSS. In CSS these are called CSS Selectors. In jQuery, these are called jQuery Selectors.

In jQuery you can chain selectors as well, like the following:

$("#main, .ad-header").text("these are new words").css("color", "orange");

This will find all the node with #main and all the nodes with the class .ad-header.

Pseudo selectors work as well, the following example will update the text in the first li within the .container block on anotheruiguy.roughdraft.io.

$(".gists li:first").css("color", "green");

Look at it this way, if you can write it in CSS, you can do it in jQuery. In fact, there are times when this helps debug your jQuery too. For example, say you have an application where you need to track various click events in the DOM. To do this, you need to write precise selectors that target specific content. An easy way to test this is to write some CSS that targets the same selectors and then in the view you can easily see what areas are targeted.

jQuery Traversing the DOM

jQuery has the ability to Traverse the DOM with native methods. Again, using Roughdraft as our example site with the inspector. The first jQuery method we will use is the .find() method to traverse like so:

$(".gists").find("li").css("color", "purple");

In this example I told jQuery to hook off the .gists selector and then .find all the li elements within and then update the CSS color.

As illustrated above, Pseudo selectors work too:

$(".gists").find("li:first-child").css("color", "purple");

$(".gists").find("li:last-child").css("color", "purple");

$(".gists").find("li:nth-child(odd)").css("color", "purple");

Instead of using CSS Pseudo selectors which can be processor heavy, jQuery has similar methods built in, like so:

$(".gists").find("li").last().css("color", "purple");

or

$(".gists").find("li").first().css("color", "lime");

How about walking the dog, I mean DOM? Using the .next() method in conjunction with the .first traversing method, we can grab the .gist selector, find all the li elements, locate the first() li in the DOM, then move to the next() DOM node and apply the inline CSS.

This process of adding more methods to the query is called 'method chaining'.

$(".gists").find("li").first().next().css("color", "orange");

To go the other direction, up the DOM, try this:

$(".gists").find("li").first().next().prev().css("color", "brown");

Walking the DOM may be necessary some times, but this is fragile as it depends on certain DOM elements to always be there and it's easy to break functionality. Updating the previous example, it's preferred to get the parent node by using the .parent() method like so:

$(".gists").find("li").parent().css("background-color", "green");

Although this is a bad example, you can simply use the .css() method on the (".gists") selector, this illustrates the principal.

Another method you can use for traversing the DOM is to be more selective and target the direct children of a node using the .children() method like so:

$(".gists").children().css("background-color", "green");