jQuery

Wenxi Zhu

Intel XDK PRC Team

What is jQuery?

jQuery is a JavaScript libraray designed to make it easier to navigate a document, select DOM elements, create animations, handle events, and develop Ajax application

 

As of 2015, jQuery remains the most widely used JavaScript library on the Web

What jQuery can do?

  • Access DOM Elements

  • Handle Events

  • Create Animations

  • Develop Ajax Applications

Access DOM Elements (1/2)

Modify the appearance of a web page:

$('ul > li:first').addClass('active');

​jQuery can change the classes or individual style properties applied to a portion of a document even after the page has been rendered.

Access DOM Elements (2/2)

Alter the content of a document:

$('#container').append('<a href="more.html">more</a>');

​Not limited to mere cosmetic changes, jQuery can modify the content of a document. Even the entire structure of the HTML can be rewritten/reordered.

Respond to a user's interaction

$('button.show-details').click(function() {
    $('div.details').show();
});

Handle the "click" event: 

Create Animations

$('button.show-details').click(function() {
    $('div.details').show();
});

Provide interactive behaviours:

The jQuery library provides an array of effects such as fades and wipes, as well as a toolkit for crafting new ones.
 

Develop Ajax Application

Retrieve server data with Ajax

With Ajax, we could retrieve information from a server without refreshing a page.
 

$('div.details').load('more.html #content');

Why jQuery?

Leverage Knowledge of CSS

In jQuery, the mechanism for locating page elements is based on CSS selectors.

$('div.content').find('p');

jQuery selectors makes it easier to retrieve the exact piece of the document that needs to be inspected or manipulated.

jQuery supports almost all the CSS selectors from CSS 1 to CSS 3.

Abstract Away Browser Quirks

jQuery adds an abstraction layer that normalizes the common tasks, tremendously simplifying the code and reducing the size of it.

Always Work with Sets

var $paraTags = $('p');

// $paraTags is an array, but we don't need to iterate it.
$paraTags.css('display', 'none'); 

Hide all <p> elements in the page:

There is NO need to loop through each returned element. 

This technique, called implicit iteration, means that many looping constructs become unnecessary.

Allows Multiple Actions in One Line

('a').addClass('current').next().show().parent().siblings().hide();
  1. Add class "current" to all <a> elements; 
  2. Display the element next to them;
  3. Hide all its parent element's siblings;

This could avoid overuse of temporary variables or wasteful repetition.

jQuery employs a programming pattern called chaining for the majority of its methods.

A Simple Example

This example can help us understand how jQuery can benefit developers:

 

 

 

 

<!DOCTYPE html>
<html>
<head>
    <title>A Simple Example</title>
</head>
<body>
    <a class="anchor">anchor1</div>
    <div><a class="anchor">anchor2</a></div>
    <div><a class="anchor">anchor3</a></div>
    <div><a class="ancho">anchor4</a></div>
</body>
</html>

Please select all the <a> elements who is the child of a <div> element and has a class of "anchor", and hide them.

Without jQuery

// Get all <div> elements in the page.
var divs = document.getElementsByTagName('div');

// Iterate all these <div>.
for (var i = 0; i < divs.length; i ++) {
    // Get all <a> elements whose parent is <div>.
    var anchors = divs[i].getElementsByTagName('a');
    
    // Iterate all these <a>.
    for (var j = 0 ; j < anchors.length; j ++) {
        // Detect if current <a> has a class of "anchor". If yes, hide it.
        if (hasClass(anchors[j], 'anchor')) {
            anchors[j].style.display = 'none';
        }
    }
}

/*
 * Return true if "element" has a class of "className"
 */
function hasClass(element, className) {
    var currentClass = element.getAttribute('class');
    return currentClass.indexOf(className) >= 0;
}

​There is a bug in the above procedure, have you noticed it?

With jQuery

$('div a.anchor').hide(); // Done. :)

Other Underlying Advantages

  • Light weight (minified version < 30 KB)

  • Open source & Free

  • Support extensions

 

So why not jQuery?

The Basics

DOM Object

The Document Object Model (DOM) is a cross-platform and language-independent convention for representing and interacting with object in HTML, XHTML & XML.

In HTML, the nodes of every documents are organized in a tree structure, called DOM tree.

A series of APIs are provided to address and manipulate the DOM tree:

// Get a DOM object.
var domObj = document.getElementById('id');

// Get the "innerHTML" property from a DOM object. 
var ObjHtml = domObj.innerHTML;              

Concept

jQuery Object

jQuery wraps the DOM object and exposes jQuery object to developers.

jQuery object can invoke property methods provided by jQuery, i.e.

document.getElementById('foo').innerHTML;

It's equal to: 

$('#foo').html();

jQuery objects can not use any of DOM object's methods, vice versa.

Concept

Transform between jQuery and DOM object

1. DOM object to jQuery object

Wrap all the DOM object with "$()":

var cr = document.getElementById('cr');  // DOM object.
var $cr = $(cr);                         // jQuery object.

2. jQuery object to DOM object

Execute the "get(index)" method provided by jQuery:

var $cr = $('#cr');            // jQuery object.
var cr = $cr.get(0);           // DOM object.

Selector

CSS Selector

In CSS, selectors are patterns used to select the elements you want to style.

Elements Selector

a { font-size: 14px}

ID Selector

#note { width: 120px}

Class Selector

.dream { display: none}

Grouping Selector

p, div, a { background-color: navy}

Descendant Selector

div p { color: gray }

Concept

jQuery Selectors

The jQuery library supports nearly all the selector included in CSS 1 ~ 3, as outlined on the World Wide Web Consortium's site: http://www.w3.org/Style/CSS/specs .

The jQuery library harnesses the power of CSS Selectors to let us quickly and easily access elements or groups of elements in DOM.

In this chapter, we will cover:

  • Basic Selectors
  • Structure Selectors
  • Attribute Selectors
  • Custom Selectors

Basic Selectors

  • Element Selectors

  • Class Selectors

  • ID Selectors

  • Grouping Selectors

  • Universal Selectors

Element Selectors

The selector is a HTML element, which serves as the most basic selectors. The selector will be one of many HTML elements such as p, h3, em, a, or even html itself.

$('div').css('background-color', 'red');
<body>
    <div>DIV 1</div>
    <div id="two">DIV 2</div>
    <div id="three">DIV 3</div>
</body>

HTML:

jQuery:

Class Selectors

The most common way to apply styles is to use class selectors. Before you can associate the styles of a class selector with an element, you must assign a class attribute to the appropriate value.

$('.panel').css('border', 'black solid 5px');
<body>
    <div>DIV 1</div>
    <div class="panel">DIV 2</div>
    <div class="panel warning">DIV 3</div>
</body>

HTML:

jQuery:

ID Selectors

Similar to class selectors, except for a few differences:

  1. ID selectors are proceeded by an '#';
  2. ID selectors refer to values found in id attributes.
$('#one').css('margin-top', '10px');
<body>
    <div id="one">DIV 1</div>
    <div class="panel">DIV 2</div>
    <div class="panel">DIV 3</div>
</body>

HTML:

jQuery:

Grouping Selectors

The easiest way to apply the same style to multiple elements.

$('div, p, .test').css('padding', '0 auto');
<body>
    <div>DIV<div>
    <p>PARAGRAPH</p>
    <span class="test"></span>
</body>

HTML:

jQuery:

Universal Selectors

This selector displayed as an asterisk (*), matches any elements at all, much like a wildcard.

$('*').css('color', 'black');
<body>
    <div>DIV<div>
    <p>PARAGRAPH</p>
    <span class="test"></span>
</body>

HTML:

jQuery:

Structure Selectors

  • Descendant Selectors

  • Child Selectors

  • Adjacent Selectors

  • Sibling Selectors

Descendant Selectors

In a descendant selector, the selector side of the rule is composed of two or more space-separated selectors. 

$('.ancestor .descendant').css('width', '300px');
<body>
    <div class="ancestor">
        <div class="parent">
            <p class="descendant"></p>
        </div>
    </div>
</body>

HTML:

jQuery:

The space between the selector is an example of a combinator. Each space combinator can be translated as "found within".

Child Selectors

Select a child of another element, rather than an arbitrarily descendant element. 

$('.parent p').css('background-color', 'red');
<body>
    <div>DIV 1</div>
    <div id="two">DIV 2</div>
    <div id="three">DIV 3</div>
</body>

HTML:

jQuery:

<body>
    <div class="ancestor">
        <div class="parent">
            <p class="descendant"></p>
        </div>
    </div>
</body>

Adjacent Selectors

Select an element that immediately follows another element with the same parent.

$('#prev + #next').css('display', 'inline');
<body>
    <div>DIV 1</div>
    <div id="two">DIV 2</div>
    <div id="three">DIV 3</div>
</body>

HTML:

jQuery:

<body>
    <div class="parent">
        <div id="prev">Prev</div>
        <div id="next">Next</div>
    </div>
</body>

Sibling Selectors

Select elements which is following siblings of another element with the same parent.

$('#prev ~ .sibling').css('display', 'inline');
<body>
    <div>DIV 1</div>
    <div id="two">DIV 2</div>
    <div id="three">DIV 3</div>
</body>

HTML:

jQuery:

<body>
    <div class="parent">
        <div class="first">First</div>
        <div id="prev">Prev</div>
        <div class="sibling">Sibling</div>
        <div class="sibling">Sibling</div>
    </div>
</body>

Attribute Selectors

  • Simple Attribute Selectors

  • Selectors Based on Exact Attribute Value

  • Selectors Based on  Partial Attribute Value

Simple Attribute Selectors

Select elements that have a certain attribute, regardless of that attribute's value.

$('a[href]').css('text-decoration', 'none');
<body>
    <div><a href="http://xdk.intel.com"></a></div>
</body>

HTML:

jQuery:

Selectors Based on Exact Value

Select elements that have a certain attribute and a certain value.

$('a[href]="http://xdk.intel.com"').css('text-decoration', 'none');
<body>
    <div><a href="http://xdk.intel.com"></a></div>
</body>

HTML:

jQuery:

Selectors Based on Partial Value

Select elements based on partial attribute value:

  1. [foo^="bar"]           Select any elements with an attribute foo whose value begins with "bar".

  2. [foo$="bar"]           ... ends with "bar'.

  3. [foo*="bar"]           ... contains the substring "bar".

  4. [foo|="bar"]           ... contains a prefix "bar".

  5. [foo~="bar"]           ... contains a space-separated value "bar".               

Custom Selectors

  • Index Selectors

  • Content Selectors

  • Visibility Selectors

Concept

Pseudo-Class and Pseudo-Element of CSS

Pseudo-class and pseudo-element are used to define special statement of a element or a special part of a document. These selectors let you assign style to structures that don't necessary exist in the document.

// Pseudo classes:
a:visited { color: red;}

a:hover { color: gray;}

// Pseudo elements:
div:first-child { margin-top: 20px;}

p:first-letter { font-size: 200%;}

jQuery leverages the syntax of CSS's pseudo class/element in its custom selectors.

Index Selectors

$('div:first');                    // Select the first element.

$('a:last');                       // Select the last element.

$('a:not(".external")');           // Select elements except for the one who has a "external" class.

$('p:even');                       // Select elements whose index is even.

$('p:odd');                        // Select elements whose index is odd.

$('span:eq(12)');                  // Select elements whose index equals to 12.

$('span:gt(12)');                  // Select elements whose index is greater than 12.

$('span:lt(12)');                  // Select elements whose index is less than 12.

Select elements based on their index.

Content Selectors

$('div:contains("test")');                    // Select elements who contains a text of "test".

$('p:empty');                                 // Select elements who don't have any content.

$('div:has("p#notes")');                      // Select div who have a child <p> whose id is "notes".

$(':parent');                                 // Select elements who have child elements.

Select elements based on their content.

Visibility Selectors

$('div:hidden').show();             // Show all hidden <div>


$('p:visible').hide();              // Hide all visible <p>

Select elements based on their visibility.

Best Known Methods

How to Remember All These Selectors?

You DON'T have to. The following 3 selectors are enough for use in 90% situations:

1. Class Selectors:

$('.myClass');

2. ID Selectors:

$('#container');

3. Descendant Selectors:

$('div p');

Why Spend So Much Time on All Those Selectors?

$('#table>tbody>tr:has(td:has(:checkbox:enabled))').css('background', 'red');

Because there is always a day, you will see a piece of shit code like this: 

For all selectors provided by jQuery, please refer to  jQuery Selectors DOC.

Manipulate the DOM

Manipulate DOM Elements

  1. Create

  2. Insert

  3. Remove

  4. Copy

  5. Replace

  6. Wrap

  7. Attributes/Properties

  8. CSS

Create Elements

Without jQuery, we have to create DOM elements with standard DOM API like this:

var anchor = document.createElement('a');

anchor.setAttribute('href', 'http://xdk.intel.com');
anchor.setAttribute('class', "external");

Create an element:

var $a = $('<a href="http://xdk.intel.com" class="external"></a>');         
var $div = $('<div></div>');         

Insert Elements (1/2)

1. append()

$('p').append('<div>Yosemite</div>');      

2. appendTo()

$('<div>Yosemite</div>').appendTo('p');

3. prepend()

$('p').prepend('<div>Yosemite</div>');      

4. prependTo()

$('<div>Yosemite</div>').prependTo('p');

The only difference between "append() / appendTo()" and "prepend() / prependTo()" is their insertion order.

Insert Elements (2/2)

5. after()

$('p').after('<div>Yosemite</div>');      

6. insertAfter()

$('<div>Yosemite</div>').insertAfter('p');

7. before()

$('p').before('<div>Yosemite</div>');      

8. insertBefore()

$('<div>Yosemite</div>').insertBefore('p');

Remove Elements

1. remove()           remove all matched elements.

$('ul li:eq(1)').remove();    

2. detach()            remove all matched elements.

$('ul li:eq(1)').detach();    

3. empty()             remove all descendant elements.

$('ul li:eq(1)').empty();    

remove() will remove matched elements and their attached events, while detach() won't.

Copy Elements

clone()                   clone all matched elements.

// Clone elements.
$('ul li:eq(1)').clone();    

// Clone with data and attached events.
$('ul li:eq(1)').clone(true);

clone() has Boolean parameter which indicates whether event handles and data will be copied with the elements. The default value is false.

Replace Elements

1. replaceWith()          replace matched elements. 

$('p').replaceWith('<strong></strong>');   

2. replaceAll()              replace matched elements. 

$('<strong></strong>').replaceAll('p');      

Wrap Elements (1/3)

1. wrap()           wrap matched elements with specified elements.

$('p').wrap('<div></div>');    
<!DOCTYPE html>
<html>
<head>
    <title>Wrap</title>
</head>
<body>
    <div><p>Paragraph 1</p></div>
    <div><p>Paragraph 2</p></div>
    <div><p>Paragraph 3</p></div>
</body>
</html>

Wrap Elements (2/3)

1. wrapAll()           wrap matched elements with a single specified                                       elements.

$('p').wrapAll('<div></div>');    
<!DOCTYPE html>
<html>
<head>
    <title>Wrap</title>
</head>
<body>
    <div>
        <p>Paragraph 1</p>
        <p>Paragraph 2</p>
        <p>Paragraph 3</p>
    </div>
</body>
</html>

Wrap Elements (3/3)

1. wrapInner()           wrap matched elements inner with specified                                           elements.

$('p').wrapInner('<div></div>');    
<!DOCTYPE html>
<html>
<head>
    <title>Wrap</title>
</head>
<body>
    <p>
        Paragraph 1
        <div></div>
    </p>
    <p>
        Paragraph 2
        <div></div>
    </p>
    <p>
        Paragraph 3
        <div></div>
    </p>
</body>
</html>

Manipulate Attributes

1. attr()                                       get / set attributes.

var title = $('p').attr('title');    // get "title".

$('p').attr('title', 'test');         // set "title" to "test".             

3. html()                                     get / set content.

$('div.container').html('<div class="content"></div>');

2. removeAttr()

$('p').removeAttr('title');   

4. height() & width()

var width = $('#box').width();
var height = $('#box').height();

Manipulate  CSS

1. css()

$('#box').css('display', 'inline-block');    

2. addClass()

$('div').addClass('current');

3. removeClass()

$('div').hasClass('current');      

4. hasClass()                   return true if elements have the class.

$('div').removeClass('current');      

Events

Handle Events

JavaScript has several built-in ways of reacting to user interaction and other events. jQuery enhances and extends the basic event-building mechanisms to give them more elegant syntax and making them more powerful at the same time.

In this chapter, we will cover:

  • Executing JavaScript Code when the page is ready
  • Handle user events, such as mouse click and keystrokes
  • Simulating events as if the user initiated them 

Concept

Performing tasks on page load

$(document).ready was jQuery's primary way to perform tasks on page load, which can achieve a similar effect of window.onload.

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

Alternate syntax for .ready()

$(function () {
    // Code here.
});

While the latter syntax is shorter, the longer version makes code more descriptive about what it is doing.

Handle User Events

  • Handle Events

  • Shorthand Events

  • Remove Event Handles

  • Event Namespace

Handle Events

Just as JavaScript allows us to intercept the page load event with <body onload="">, it provides similar hooks for events such as mouse clicks (onclick), form fields being modified (onchange), and window changing size (onsize).

jQuery offers an improved way of handling these events: 

$('#switcher').on('click', function() {
    // Code here ... 
});

Multiple calls to .on() coexist nicely, appending additional behaviors to the same event as necessary.

Shorthand Events

Binding a handler for an event (such as a simple click event) is such a common task that jQuery provides an even terser way to accomplish it.

Shorthand event methods work in the same way as their .on() methods 

$('#switcher').click(function() {
    // Code here ... 
});

Remove Event Handles

We can accomplish this by calling the .off() method to remove handles:

$('#switcher').click(function() {
    // Click handler 1.
});

$('#switcher').click(function() {
    // Click handler 2.
});

// Remove handlers. Both handlers have been removed now.
$('#switcher').off('click');

There is an side-effect of .off() method, that all handlers will be removed.

Event Namespaces

In order to make .off() call more specific so that it does not remove all handlers. One way to doing this is to use the event namespaces:

$('#switcher').on('click.one', function() {
    // Code here ...
});

$('#switcher').on('click.two', function() {
    // Code here ...
});

// Only remove the "click.two".
$('#switcher').off('click.two');

The .one and .two suffix is invisible to the event handling system, "click" events are handled by these two functions.

Simulating User Interaction

At times, it is convenient to execute code that we have bound to an event, even if the normal circumstances are not occurring.

$('#switcher').trigger('click');

Simulate a "click" event with .trigger() .

The .trigger() method provides the same set of shortcut methods that .on() does.

$('#switcher').click();

Animations

Concept

jQuery Animation

With jQuery, we can easily add impact to our actions through a set of simple visual effect and even craft our own more sophisticated animations.

 

The effects offered by jQuery supply simple visual flourishes that grant a sense of movement and modernity to any page. However, apart from being more decoration, they can also provide important usability enhancement that help orient the user when there is  some change on a page (especially common in Ajax application). 

jQuery Animation

  • Hide / Show

  • Fade In / Fade Out

  • Slide Up / Slide Down

Hide / Show

The basic .hide() / .show() methods without parameters, will immediately hide / show elements.

$('p:eq(2)').hide();

$('#button').click(function() {
    $('p:eq(2)').show();
});

Effects and Duration

When a duration is included with .show() or .hide(), it becomes animated - occurring over a specified period of time.

The hide(duration) method, for example, decreases an element's height, width, and opacity simultaneously until all three reach zero.

The .show(duration) method will increase the element's height from top to bottom, width from the left-hand side to the right-hand side, and opacity from 0 to 1 until its contents are completely visible.

 

$('p:eq(2)').hide(600);

$('#button').click(function() {
    $('p:eq(2)').show(600);
});

Concept

Speed in

With the jQuery effect, we can use one of the two speeds 'slow' or 'fast'. Using .show('slow') makes the show effect complete in 600 milliseconds, .show('fast') in 200 milliseconds. If any other string is supplied, jQuery's default animation duration of 400 milliseconds will be used. 

$('p:eq(2)').hide('slow');

$('#button').click(function() {
    $('p:eq(2)').show('fast');
});

Concept

Fade In / Fade Out

To have the elements appear by increasing / decreasing the opacity, we can use .fadeIn() and .fadeOut() instead. 

$('p:eq(2)').fadeIn('slow');

$('#button').click(function() {
    $('p:eq(2)').fadeOut('slow');
});

Slide Up / Slide Down

These effects animate only the height of the selected elements.

$('p:eq(2)').slideUp('slow');

$('#button').click(function() {
    $('p:eq(2)').slideDown('slow');
});

Ajax

Ajax

The term Asynchronous JavaScript and XML (Ajax) was coined by Jasse James Garrett in 2005. Since then the term encompasses a group of related capabilities and techniques.

In this chapter, we will cover:

  • Loading data from a server
  • Sending data back to a server
  • Interpreting data in a variety of formats, including HTML, XML and JSON 

Concept

XMLHttpRequest

The XMLHttpRequst allows requests to be made to the server without interrupting other browser tasks.

var xhr = new XMLHttpRequest();

xhr.open('GET', 'test.html', true);

xhr.onreadystatechange = function() {
    if (this.readyState === 4) {
        if (xhr.status === 200) {
            // Get response.
            var response = this.responseText;
        }
    } 
};

xhr.send(null);

Unsurprisingly, browsers are not entirely consistent with regard to their implementation of the XMLHttpRequest object. 

Append HTML

Ajax applications are often no more than a request for a chunk of HTML. This technique, sometimes referred to as Asynchronous HTTP and HTML (AHAH).  

$('#dictionary').load('a.html');
<html>
    <body>
        <div id="dictionary">
        </div>
    </body>
</html>
<ul>
    <li>Abdication</li>
    <li>Absolute</li>
    <li>Acknowledge</li>
</ul>

index.html

a.html

Retrieve JSON

The term JavaScript Object Notation (JSON) was coined by Douglas Crockford to capitalize on this simple syntax.

This notation can offer a concise alternative to the bulky XML format:

{
    "name": "xdk",
    "edition": ["typical", "iot"]
}

JSON can be retrieved by $.getJson().

$.getJSON('b.json', function(data){
    for (var property in data) {
        console.log(data[property]);
    }
});

Execute Scripts

A elegant way to inject additional JavaScript code via jQuery:

$(function() {
    $('#button').click(function() {
        $.getScript('c.js');
    });
});

We could introduce the <script> tags on the fly when they are needed, but $.getScript() is a more elegant way.

Pass Data to Servers

Perform a GET requst:

$.get('e.html', requestData, function(data) {
    console.log(data);
});

Perform a POST requst:

$.post('e.html', requestData, function(data) {
    console.log(data);
});

GET places its arguments in the query string portion of the URL, whereas POST request does not.

The Low-level Ajax Method

Rather than presuming one particular type of Ajax activity, this function accepts an object containing options that can be used to customize its behavior.

We have seen several methods that all initiate Ajax transactions. Internally, jQuery maps each of these methods onto variants of the $.ajax() global function.  

$.ajax({
    url: 'server.html',
    success: function(data) {
        $('#dicitonary').html(data);
    }
});

Questions?

jQuery

By zhuwenxi

jQuery

  • 1,769