Ch. 22: An Introduction to jQuery

• Understand how to include jQuery in your HTML.

• Understand important jQuery concepts and syntax.

• Use jQuery with your webpages.

jQuery Primer

- jQuery syntax is also easy to learn; it uses a simple namespace and consistent functionality.

- Used together with the jQuery User Interface (UI) add-on (covered in Chapter 23), you can create powerful, highly interactive web applications.

Using jQuery

• The Two jQuery Downloads

- a production version and a development version.

⇒ Unless you’re planning to develop jQuery plug-ins, or need to look at the internals of jQuery, you should download and use the minified production version.

- content delivery network (CDN): to access a hosted version of jQuery.

⇒ Google hosts jQuery and other libraries through its API website.

http://code.google.com/apis/libraries/devguide.html

- Using the local version can be faster and more reliable than using the CDN version.

• Including jQuery

<!DOCTYPE HTML PUBLIC  "-//W3C//DTD HTML 4.01//EN"  "http://www.w3.org/TR/html4/strict.dtd">

<html>

<head>

<title>Adding jQuery</title>

<script type="text/javascript" src="jquery-1.4.3.min.js"></script>

</head>

<body>

</body>

</html>

• Basic jQuery Syntax

- there’s a shortcut to the jquery() function: $()

⇒ Rather than typing jquery each time, you access the jQuery library using a dollar sign followed by parentheses

e.g., Table 22-1: A Few jQuery Selectors

$(“a”) - All <a> elements in the document.

$(document) - The entire document, frequently used to access the ready() function shown later in this chapter.

$(“#elementID”) - The element identified by ID elementID.

$(“.className”) - The element or elements that have the className class.

- Syntax: Selector.Function;

⇒ jQuery uses functions to perform actions on selected elements. Functions can be built-in to jQuery or user-defined. You almost always end up using both at the same time.

- Like JavaScript code, jQuery statements should end with a semi-colon.

⇒ you can use either single or double quotation marks as selectors within jQuery.

e.g., $("a"), $('a')

• Connecting jQuery to the Load Event

- Connecting to elements during the load (or onload) event of the page.

⇒ In jQuery, you do this through the .ready() utility function of the document element.

Example)

Chaper22\CompletedCode\docready.html

//<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"> </script>

ITCookBook: Chap15/1503/1503_end.htm

- This mixture of jQuery and JavaScript, alert('hi') is an important concept to understand

⇒ you use jQuery to supplement normal JavaScript.

- The $(document).ready() function removes the need for you to use the browser’s load event or to insert a function call into the load event.

⇒ With $(document).ready(), all the elements of the Document Object Model (DOM) are available before the .ready() function.

Using Selectors

- You use selectors to identify and group the elements on which a jQuery function is executed.

- Selectors and the way they work in jQuery are based on selectors in CSS.

⇒ If you are comfortable with using them in CSS, you will feel right at home with this model.

• Selecting Elements by ID

- $("#elementID")

e.g., consider this bit of HTML:

<a href="#" id="linkOne">Link</a>

getElementById("linkOne") // With normal JavaScript, you access this element like so:

$("#linkOne")  // With jQuery, you access the element using this:

PL-JavaScript: 1CanvasIntro/0MyCodes/Canvas1.html

• Selecting Elements by Class

- $(".className")

e.g., here’s a 'div' with a class applied:

<div class="specialClass">

$(".specialClass") // You would access that element through jQuery like this:

- Bear in mind that you might not be accessing a single element;

⇒ the class selector accesses all elements for which the specified class is applied.

• Selecting Elements by Type

- Using a type selector provides access to all the elements of the specified type on a page.

e.g., such as all <div> elements, all <a> elements, and so on.

$('div')

$('a')

• Selecting Elements by Hierarchy

- you can select elements by their position in relation to other elements on the page.

e.g., to select all the <a> elements that are within <div> elements, you use this syntax:

$("div a")

e.g., if you want all the anchors that followed only a specific div, you combine the type selector with the ID selector syntax.

Consider this HTML:

<div id="leftNav">

<a href="link1.html">Link 1</a>

<a href="link2.html">Link 2</a>

</div>

$("#leftNav a")

• Selecting Elements by Position

- jQuery offers several ways to select more specific elements within a group.

e.g., The following code selects the first <p> within the page:

$("p:first")

Likewise, the last element is selected like this:

$("p:last")

e.g., consider this HTML:

<p>First Paragraph</p>	// $("p")[0], $("p:eq(1)")

<p>Second Paragraph</p>

<p>Third Paragraph</p>

To select the second <p> element, you use this syntax:

$("p")[1]

To choose the third paragraph, you could write:

$("p:eq(3)")

⇒ When possible, it’s better to use an ID selector to choose an individual or specific element than to rely on an element’s position.

- another sometimes useful set of positional selectors are even and odd, which select every other element in a set:

$("p:even")

⇒ The even and odd selectors are quite helpful when working with tabular data to alternate row colors.

Example)

Chaper22\listing22-2.html

//<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"> </script>

⇒ The code uses the $(document).ready() function along with the :odd selector to set the background color to hexadecimal #abacab—a light gray color.

• Selecting Elements by Attribute

- jQuery lets you select elements that merely contain an attribute or those that contain an attribute with a specific value.

e.g., to select all images that have an alt attribute, you write this:

$("img[alt]")

e.g., Selecting only images that have an alt attribute set to a certain value looks like this:

$("img[alt='alternate text']")

$('img[alt="alternate text"]')

⇒ Any variation of that, such as “alternate text 2” or “ alternate   text ” would not match.

- jQuery includes wildcard selectors that don’t require an exact match on attributes.

e.g., Table 22-2: Attribute Selector Matching

attribute*=value : the attribute for which the attribute value contains the specified value as a substring.

attribute~=value : the attribute for which the attribute value contains the specified value as a whole word.

attribute!=value - Selects elements that either do not contain the attribute or for which the attribute value does not match the specified value.

attribute$=value - the specified attribute for which the attribute’s value ends with the specified string.

attribute^=value - the attribute for which the attribute’s value begins with the specified string.

• Selecting Form Elements

- jQuery contains native selectors related to web forms.

e.g., Table 22-3: Form-related Selectors

:checkbox - Selects all check boxes

:checked - Selects all elements that are checked, such as check boxes

:input - Selects all input elements on a page

:password - Selects all password inputs

:radio - Selects all radio button inputs

:reset - Selects all input types of reset

:selected - Selects all elements that are currently selected

:submit - Selects all input types of submit

:text - Selects all input types of text

• More Selectors

- Refer to http://api.jquery.com/category/selectors/ for more information.

Functions

- jQuery uses functions to perform actions on selected elements.

⇒ Functions can be built-in to jQuery or user-defined.

⇒ You almost always end up using both at the same time.

• Traversing the DOM

- the .each() function takes a list of selected elements and iterates over each of them, doing something (or nothing) to each as it loops through the list

- traversing: the traversing-related functions

⇒ http://api.jquery.com/category/traversing/

- the $(this) selector refers to the current object — the item currently being traversed.

⇒ the 'this' keyword in object-oriented programming,

Example)

Chaper22\listing22-3.html

//<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"> </script>

⇒ For any team whose Win/Loss percentage is at or above .500 (meaning they’ve won at least half of their games), this example applies a boldface font to their field.

Example)

Chaper22\listing22-4.html

It would be even nicer to apply the boldface font weight to the entire table row.

⇒ Applying the parent() function essentially moves up the DOM tree to find the <tr> tag that encloses this particular <td> element.

⇒ By applying the CSS style change to the <tr> element, you can make the entire row boldface.

- Chaining is a powerful construct in jQuery.

⇒ It enables additional levels of selection as well as multilevel application of functions.

⇒ In this example, the $(this) selector is chained to the .parent() function, which further selects the parent of $(this).

- changing the style or presentational aspects of a webpage through JavaScript is not recommended.

⇒ It’s better practice to apply or remove styles through CSS rather than change attributes directly.

⇒ Several methods exist to work with CSS style classes using jQuery.

⇒ .hasClass(), .addClass(), .removeClass(), and .toggle-Class().

⇒ http://api.jquery.com/category/css/

• Working with Attributes

- jQuery has functions to work with attributes of the DOM.

⇒ The most generic of these is the .attr() function, although others, such as .html() and .val(), are useful as well.

- You use the .attr() function to both retrieve and set attributes.

e.g., you can both retrieve and set an image’s alt attribute.

<a href="./Myhome/Music/god.swf">

<IMG src="./Myhome/Java/m_any.gif" width="46" height="46"

border="0" alt="[Interview]">

// Get the alt attribute:

$("#myImageID").attr("alt")

// Set the alt attribute:

$("#myImageID").attr("alt", "new text")

ITCookBook: Chap5

<img> 태그의 속성: src, alt, width, height, align, border, hspace, vspace

• Changing Text and HTML

- you need to rewrite portions of HTML within a page or change text or values.

- The .html() function retrieves or changes the entire HTML within a selected element.

e.g., consider this HTML:

<div id="myDiv">Here is a div, it's quite nice</div>

$("#myDiv").html('<span class="redStyle">This is the new content of the div</span>');

⇒ The outcome of this bit of jQuery is that the <div> identified by myDiv would now contain a <span> element with new text in it.

- the text() function supports both retrieval and setting of the text within a selected element.

⇒ Unlike HTML, the .text() function changes only the text.

e.g., Android: 0Mycodes\1-10.html

e.g., <div id="myDiv">Here is a div, it's quite nice</div>

$("#myDiv").text('This is the new content of the div');

⇒ only the text changed.

• Inserting Elements

- after() and before()

⇒ they add elements either after or before a selected element, respectively.

e.g., <div id="myDiv">Here is a div, it's quite nice</div>

// And here’s some jQuery that inserts another div before it:

$("#myDiv").before("<div>This is a new div</div>");

//The :after() function works in a similar fashion:

$("#myDiv").after("<div>This is a new div, it appears after myDiv</div>");

⇒ When run, the page containing this code would have three <div> elements:

<div>This is a new div</div>

<div id="myDiv">Here is a div, it's quite nice</div>

<div>This is a new div, it appears after myDiv</div>

• Callback functions

- merely a grouping of code that gets called within another function.

⇒ A callback function executes after its parent function completes.

⇒ jQuery uses of callback functions heavily, especially in AJAX.

e.g.,  <script type="text/javascript">

$(document).ready( function() {

$('tr:odd').css("background-color", "#abacab");

$('.percentage').each( function() {

if ($(this).text() >= .5) {

$(this).css('font-weight', 'bold');

}

});

});

</script>

- http://docs.jquery.com/Tutorials:How_jQuery_Works

Events

- jQuery enables your programs to respond to mouse clicks, form submissions, keystrokes, and more.

⇒ Unlike JavaScript, cross-browser event handling in jQuery is quite easy.

- jQuery thrives in a cross-browser environment.

⇒ This is especially true in event handling.

• Binding and Unbinding

- .bind(event, data, handler)

⇒ event is the event to which you want to respond,

data is an optional object containing additional data to be passed into the event handler, and

handler is the function that you want to run in response to this event.

e.g., <a href="/link1.html" id="myLink">A link</a>

$("#myLink").bind("click", function() {

alert("clicked the link");

});

- You can bind the following events with the .bind() function:

beforeunload,	blur,	change

click,	dblclick,	error

focus,	focusin,	focusout

hover,	keydown,	keypress

keyup,	load,	mousedown

mouseenter,	mouseleave,	mousemove

mouseout,	mouseover,	mouseup

resize,	scroll,	select

submit,	toggle,	unload

e.g., ITCookBook: Chap15/1500eventhandler/eventhandler.htm

- jQuery’s .bind() function is much better at cross-browser event handling and much more powerful than the ehandler.js script in Chapter 11.

- jQuery also provides shortcut functions that perform the same way as .bind().

⇒ .click( function() )

e.g., $("#myLink").click( function() {

alert("clicked the link");

} );

- Not only can you respond to events such as clicking a link, but you can also trigger events.

Example) Chaper22\listing22-5.html

$('#myDiv').click( function() {

$('#braingiaLink').click();	// you can also 'trigger' other events.

} );

⇒ clicking anywhere within the <div> triggers the click event for the anchor, as if you had clicked the anchor itself.

- To stop responding to events, you can unbind them using the .unbind() function.

.unbind(event, function)

• Mouse Events and Hover (float, fly)

- you can also work with mouse events such as mouseover and mouseout.

⇒ One fun thing to do is to make items disappear when a user moves the mouse over them.

Example) Chaper22\listing22-6.html

⇒ makes an anchor disappear when the mouse moves over its containing paragraph.

$('#wrapperP').mouseover( function() {

$('#braingiaLink').hide();

} );

$('#wrapperP').mouseout( function() {

$('#braingiaLink').show();

} );

⇒ When the mouse enters this paragraph, the anchor identified by braingiaLink disappears, only to reappear when the mouse leaves the paragraph area.

- jQuery also has a .hover() function that performs much like the .mouseover() and .mouseout() events.

⇒ http://api.jquery.com/hover/

• Many More Event Handers

- there are numerous other event handlers in jQuery — too many to cover in a single introductory chapter on jQuery.

⇒ http://api.jquery.com/category/events/

AJAX and jQuery

• Chap. 19: Introduction to AJAX

- Without AJAX, a web application might make the visitor wait while a response is gathered from the web server.

⇒ An AJAX-based application sends requests from the web browser to the web server in the background (asynchronously) while the visitor is using the application.

⇒ This makes the application feel much more responsive to the user.

- jQuery has its own methods for working with AJAX.

⇒ jQuery makes using AJAX easier.

- jQuery offers several functions for working with data from and sending data to a server.

⇒ the .post() function, and the .get() function.

e.g., JSP: Chap 3 - GET and POST

-jQuery also includes a specific AJAX function, aptly titled .ajax().

⇒ http://api.jquery.com/jQuery.ajax/

- The basic syntax of the ajax() function is:

$.ajax({

parameter: value

});

e.g., $.ajax({

url:  "testajax.aspx",	// URL

success:  function(data) {	// callback function

alert("Successful load");

}

});

⇒ you typically specify the method, the URL, and a callback function.

⇒ It’s also quite common to specify the data type to be returned, whether to cache the response, the data to be passed to the server, and what to do when an error occurs.

e.g., For this example, assume that the JSON-encoded data is returned when the file json.php is called on the local server.

⇒ The following use of the .ajax() function retrieves the data and calls a function named showStates when successful:

$.ajax({

type: "GET",

url: "json.php",	//  remore procedure (PHP must be set up)...

dataType: "json",	// JSON (JavaScript Object Notation	//        - 자바스크립트 객체표기 방법)

success: showStates

});

• AJAX Errors and Timeouts

- you can specify an error handler with the error parameter.

$.ajax({

type: "GET",

url: "json.php",

dataType: "json",

success: successFunction,

error:  errorFunction

timeout: 5000	//in milliseconds

});

function errorFunction(xhr, statusMessage, exceptionObj) {

alert("An error was encountered " + statusMessage);

}

⇒ The callback function used for error handling (errorFunction in the previous code example) receives three arguments.

⇒ the XMLHTTPRequest object;

a string representing the error encountered;

an exception object, if an exception occurred.

⇒ an error handler function should accept these three arguments and then do something with the results.

- You can set a generic AJAX timeout value through the default $.ajaxSetup.

⇒ but you can also specify a timeout value for any individual call using the timeout parameter

• Sending Data to the Server

- You not only need to receive data from a server in an AJAX call, but also to send data to a server and receive a response.

⇒ You use the data parameter to the .ajax() function for this, sending data using either GET or POST.

- You can format the data as ampersand-separated key=value pairs (key1=value1&key2=value2) or as mapped pairs {key1: value1, key2: value2}.

Example) Chaper22\listing22-7.html

⇒ This example calls a server-side program titled statefull.php, which, given a two-letter state abbreviation returns the full name of the state. i.e., 'Wisconsin'

$.ajax({

type: "POST",

url: "statefull.php",	// remote procedure

dataType: "json",

success: successFunction,

data: "state=WI"	// send data to a server, i.e., keyword

});

• Other Important Options

- The async option, which is set to true by default,

⇒ informs the script whether it should wait (and block further input in the browser) while the AJAX transaction is sent, received, and processed.

⇒ When set to true, the AJAX transaction is done asynchronously, so it does not block.

- The cache setting, which defaults to true in most instances,

⇒ controls whether jQuery will cache the AJAX transaction.

⇒ This is useful when the data being received doesn’t change often, because caching speeds up the transaction,

⇒ but caching can cause problems when your application is using older cached data that has changed on the server.

⇒ it helpful to set this option to false so that the response is not cached.