GeorgieP

reading and tinkering

The Basics: DOM, $ and selectors

Intro

A look ahead. jQuery is just JavaScript. $ is shorthand for calling the jQuery object. jQuery uses css style selectors to get DOM elements, to which jQuery methods can be stringed on to. For example: $('.article').css('color','purple');

Is calling jQuery to get an element or elements with the class of 'article', and them setting the color to purple with the css method.

Note that the jQuery selects DOM elements with a string, as are the arguments for the methods. JavaScript variable can be passed too.

A lot of the course will be about using the jQuery documentation.

Why does jQuery exist?

jQuery IS JUST JAVASCRIPT!!!111OMGWTF!

jQuery exists because manipulating the DOM with plain JavaScript isn't always easy. It's much more long-winded, and therefore error-prone. James showed and example of adding an element to a page, which is 4 steps in JavaScript and 1 step in qQuery.

It also takes away all the headaches of browser compatiblity. And some other advantages I don't understand yet, like AJAX stuff. It let's you focus on UX (user experience).

What is jQuery actually?

James demo'd that typing jQuery into the console returns a function -- which is also an object, as all JavaScript functions are objects. He then did the same demo with the $ sign, showing that it is used as shorthand for jQuery. Note: the $ is just a variable and can be overwritten / reassigned accidentaly, and that some other JavaScript libraries also use the $ in a similar fashion, so you should be aware of potential clashes.

How to use the $

Calling $ returns a jQuery Collection which is very similar to a JavaScript array - BUT with additional methods.

When you pass a string into the jQuery objects a jQuery Collection of DOM elements is returned. e.g.: $('#someID');

You can also pass a function into the jQuery object, and even a DOM element like: $(body);

You can call methods directly on the $ object, like .each() : $.each(); or $.ajax();. James also mentioned the Udacity AJAX class, which I could probably do with taking, someday, since I have no clue what it's all about. Why do I keep calling him James? That was the lovely black southern guy, this guy's name is Cameron Pittman or something.

DOM Inspiration

The DOM is a tree structure. Cameron explained the concepts of children, siblings, parents, nested elements etc.

How is jQuery added to a page?

Just like any JavaScript, using script tags, in the head, in the body, etc. It can be served from a CDN, which had the advantage of caching (and saving your visitor from having to download the library again) or from your own site. CDNs are super fast too, and will probably always be way faster than your own site.

Don't forget to use the minified version of jQuery in production, as it is seriously smaller

Select by tags

The jQuery docs on selectors.

This exercise shows getting all list elements in a DOM and it is the first time we see the format of that weird jQuery indexed array.

Select by classes / Select by ids

Selecting by tags is bad.

Select by classes is better as it is more specific (assuming you are writing half-decent HTML). Remember to add the CSS selector like a . for classes and a # for ids.

(Family Tree Revisited) jQuery DOM Traversal Methods

jQuery docs on traversal methods.

Note: .parent() only gets the immediate level above the selector, while .parents() will select all of the parents. You can pass another selector into .parents() to refine the selection.

Likewise, .children() only selects one level below. To go further below, Cameron recommended using .find() to get all sub-levels and them pass a selector into .find() to be more specific.

Note that .parent() and .children() only traverse one level. .parent() only returns a single item. .siblings() returns a group of siblings and also takes a selector to let you get more specific.

Filtering

Cameron dropped in a link on filtering but didn't discuss it yet. In the quiz it didn't actually use any filtering methods either? He passed another selctor to a traversal method and called that a filter, but that's not what the filter methods link was about at all! That was helpful. The sneaky snakey git.

Note that Cameron used the universal selctor '*' inside .find('*') as the selector is not optional. Using '*' is allowed, and is used as you would think. He took the opportunity again to show this is the first thing they tell you when you look at the docs for .find() on the jQuery website.


The Tricks: DOM Manipulation

jQuery documentation and me, who me? yes me

A description of what's to come, then a look at the website docs and the .addClass('className') method under attributes. Went on to show that you can also pass a function to the addClass method like $('selector').addClass(function);, the function has to return (or evaluate to) a string. The addClass method can also take multiple class names seperated by spaces.

If the documentation shows a method being passed a parameter enclosed in square brackets .parents(['selector']), this denotes it is optional.

me.toggleClass('className')

A look at the .toggleClass('className') method. Note the class name is being passed as a parameter and is not being used as a CSS style selector - this means it is not preceded with a '.' or '#'.

.next(['selector'])

The next method gets the immediately following sibling of each element in the set of matched elements. This was quite tricky to get my head around, multiple selections and then shifting all those selections by one.

If a selector is passed, it gets the next sibling only if it matches that selector.

Changing Attributes

The $('selector').attr('attribute', 'value'); method is very interesting in that if you pass one parameter it returns the value, but if you pass two parameters it sets the attribute and value.

This will be a common pattern in use in jQuery.

The quiz also showed the $('selector').first(); method, which references the first item in a collection.

Modifying css

Note that adding CSS with jQuery adds inline style tags to the HTML and does not add styles to the CSS file, as you would prefer. So, really it shouldn't be used.

The syntax is: $('selector').css('property','attribute'); but can also take functions that evaluate to strings.

Pulling html and text

.html() will get or set all the everything between a set of tags, but .text() will only get or set the text and strip all the html from what was referenced.

.val() is a great way to get to the contents of a lable or other elements.

Removing DOM elements

.remove(['selector']) does exactly what it says on the tin.

$( "p" ).remove( ":contains('Hello')" ); - a nice example using :contains from the jQuery docs.

MmmmHmmmm. Now we know what happened to James.

Adding DOM elements

Note that both insertBefore and insertAfter can be used to do multiple insertions around a target selection that found a collection.

For a more 'normal' pattern you can use $('selector').before(content) and $('selector').after(content) instead.

Iterating with .each(function)

Iterates over a jQuery object, executing the function on each matched element. Note you must use $(this) to refer to the element currently being iterated on.

Example:

          $( "li" ).each(function( index ) {
            console.log( index + ": " + $( this ).text() );
          });
        

Note that 'index' was used here optionally.

Why use jQuery?

Why is jQuery so popular?

Note, technically it should slow pageloads, but in practice it will probably speed them up. Udacity's tip is to use a minified version from a CDN to make it even faster.

$ Ready when you are

In the last section we are reminded that any that uses the jQuery ($) call runs on document.ready which makes life very simple an can (and has been for me) a pain for beginners. Just using jQuery instead, avoids all these issues.

Apparantly, this is something to do with callback too... :/

What Next?

Other notes and resources

I looked at the Microsoft Virtual Academy Intro to jQuery course which was very interesting but suffered from the fact that is gives no exercises or practice. A real pity becuase it had much better content and covered a lot more, as beginner's Intros go, I thought.