jQuery

What is jQuery

providing a standard to access the DOM that is consistent across different browsers

providing an easy API that wraps JavaScript

Basic jQuery

jQuery is based on using CSS selectors to select elements in the DOM and methods to perform operations on them. For instance:

jQuery('h1').text('Hello World')// set value of h1 to "Hello World"$('h1').text('Hello world')// the $ sign is a short notation for jQuery

Whenever we use jQuery, it is important that we wait for the DOM to be fully loaded beforr we start interacting with it. To make sure of this, we use the ready method. The ready method lets us set a callback that will be executed when the DOM is fully loaded.

$(document).ready(function{// this is the jQuery ready event handler is executed when the DOM has been loaded$("h1").text("Hello world");// set value of h1 to "Hello World"});

Using Selectors

jQuery lets you use any CSS selector and pseudo classes to select all the elements in the DOM that match those selectors. For instace:

$('ul#grocerylist li:first')// select first li that is a descendant of the ul element with id grocerylist$('ul#grocerylist li:last')$('ul#grocerylist li:even')// selects li elements with even index (0, 2, 4)$('ul#grocerylist li:odd')

$('li').first().next()// next sibling$('li').last().prev()// previus sibling$('li').first().parent()// parent element$('ul').first().children('li')// children - unlike find this selects direct children$('li').parents('.awesome')// walk up the dom to find all ancestors of class awesome (returns all elements that satisfy that condition)$('li').closest('.awesome')// walk up the dom to find the closest ancestor (returns 0 or 1 elements)

The point of using traversing is that it is faster than the alternative (via normal selectors).

Filtering the DOM via traversing

Manipulating the DOM

These are the operations you can do to manipulate the DOM:

var message =$('<p>Hello! this is a paragraph</p>')// Create paragraph element// add element as a child of div#screen and at the end of the children tree$('div#screen').append(message)
message.appendTo($('div#screen'))// add element as a child of div#screen and at the beginning of the children tree$('div#screen').prepend(message)
message.prependTo($('div#screen'))// add element as a sibling of the first paragraph and after it$('div#screen p:first').after(message)
message.insertAfter($('div#screen p:first'))// add element as a sibling of the first paragraph and before it$('div#screen p:first').before(message)
message.insertBefore($('div#screen p:first'))// remove first paragraph$('p:first').remove()

Styling the DOM

You can explicitly set the css of elements via the css method:

$("p:first").css(<attribute>,<value>);// set attribute$("p:first").css(<attribute>);// get attribute$("p:first").css(<object>);// set several attributes at once

Or you can add, remove and toggle classes of elements (which is a better practice since it helps enforcing the separation of concerns between behavior - javaScript - and styling - CSS):

$('p:first').animate({ top:'10px'})// changes css property in an animated manner$('p:first').animate({ top:'10px'},400)// you can explicitely set the speed of the animation in milliseconds$('p:first').animate({ top:'10px'},'fast')// or with a special string 'fast', 'slow', etc$('p:first').animate({ top:'10px'},200)$('p:first').animate({ top:'10px'},'slow')$('p:first').animate({ top:'10px'},600)

Today, you can specify most animations using CSS3 transitions and CSS3 animations. However you still need to use vendor prefixes and “modern” browsers for it to work.

Interacting with events in the DOM

Event handling with jQuery usually takes the shape of $("element").method(eventHAndler) or $("element").on(eventName, eventHandler).

$("button").on("click",function(){// callback that runs when any button is clicked});$("button").click(function(){...})

We can use the $(this) to refer to the element that triggered the event inside an event handler.

Using event delegation

Using event delegation we limit the elements that we associate to events:

$(".groceries").on("click","button",function(){//...});

Using event arguments

Every event in jQuery gets passed the same event argument:

$('button').on('click',function(event){// callback that runs when any button is clicked})

Sending data with AJAX post calls

Effects

Chaining Effects and Adjusting Speed

$("#login").fadeOut().html(...).fadeIn();// doesn't wait for the end of fadeOut to change the html$("#login").fadeOut("fast",function(){// waits for the fadeOut to complete before executing the callback$(this).html(...).fadeIn("slow");})

Effect Easing

jQuery offers two easing effects by default: linear and swing. jQuery UI comes with a lot of easing effects.

$('#login').fadeOut(1000,'swing')

Queueing Effects

We can queue effects by using the queue method like illustrated bellow:

$('#login').queue(function(next){$(this).html('...').fadeIn('slow')next()// use next to dequeue the next item})

Delay Effects

You can delay effects by using the delay method:

$('#toast').delay(1000).fadeIn()

You can also use the stop method to stop any effect at any time.

jQuery Helpers

jQuery offers several helpers like $.each for traversing collections:

$.each(swords,function(index, sword){...});

and $.map to perform transformations:

$.map(swords,function(sword){...});

Create Your Own Helpers

You can easily extend jQuery with your own helpers (methods not called on jQuery objects but called just by using the $. notation):

Would you like to receive more articles like this one on programming, web development, JavaScript, Angular, developer productivity, tools, UX and even exclusive content like free versions of my books in your mailbox? Then sign up to my super duper awesome inner circle.

Did Ya Know I've Written Some Books?

I have! The JavaScript-mancy series is the lovechild of three of my passions: JavaScript, writing and Fantasy. In the pages of each one of the books of the series you’ll find a breadth of JavaScript knowledge, delivered with a humorous and casual style of writing and sprinkled with Fantasy at every turn.

They are the weirdest and quirkiest JavaScript books you'll ever find. There's nothing out there quite like it.