Intertech‟s Oxygen Blast Series July 2010

An Intertech Course

OxygenBlast - Understanding jQuery

• Jason S. Shapiro – jshapiro@intertech.com

• Twitter: @intertechinc – http://twitter.intertech.com
• ~15 Years Professional Software Development and Architecture Experience • Master of Science in Software Engineering • Sun Certified Java Programmer & Web Component Developer • Scrum Alliance Certified ScrumMaster
Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 2

OxygenBlast - Understanding jQuery

• • • • • • •

Welcome What is jQuery? jQuery Setup jQuery‟s Identifiers Method Chaining Selecting Elements Ajax Utilities

Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 3

Intertech.OxygenBlast . Inc.com • 800-866-9884 • Slide 4 .Understanding jQuery • • • • • • DOM Creation and Manipulation Event Handling Adding Styles & Effects UI Library Overview jQuery Resources Questions Copyright © Intertech. 2009 • www.

NET course.com • 800-866-9884 • Slide 5 . 2009 • www. Inc.Intertech.OxygenBlast . Copyright © Intertech. • Complete Ajax for Java: • • • • • Advanced JavaScript HTTP DOM API Testing & Debugging Security • We also offer a Complete Ajax for .Understanding jQuery • Many of the prerequisites for this webinar are taught in our Complete Ajax courses.

Inc.0+.OxygenBlast . released in 2006.” This framework is free and licensed under the MIT and GNU General Public License. Their motto is “write less. is an open-source JavaScript framework with a large number of widgets and 3rd party plug-ins.Understanding jQuery • jQuery.Intertech. Version 2. IE 6+. Opera 9+.com • 800-866-9884 • Slide 6 . • • • • Its primary focus is to ease the complexity of coding JavaScript and Ajax applications. Copyright © Intertech. Safari 3+. 2009 • www. do more. Browser support includes Firefox 2. and Chrome 1+.

http://trends. Microsoft.com/javascript) jQuery is used by Google. • One stats Web site listed jQuery as “the most detected JavaScript library in use on the web” by a wide-margin.OxygenBlast . among others. IBM.Intertech.com • 800-866-9884 • Slide 7 .Understanding jQuery • jQuery is arguably the most popular JavaScript framework available.builtwith. • • jQuery was created by John Resig who currently leads the project‟s development team. Dell. Amazon. NBC. Inc. (July 2010 .org/team Copyright © Intertech. 2009 • www. • • Resig is also a JavaScript Tool Developer for the Mozilla Corporation You can find out more about the development team. along with links to their blogs and Twitter accounts at: http://jquery.

Intertech. Inc.com • 800-866-9884 • Slide 8 . found at http://www.jquery.Understanding jQuery • The entire core jQuery API is a single JavaScript file. 2009 • www.com Copyright © Intertech.OxygenBlast .

com • 800-866-9884 • Slide 9 . there are two primary versions of the jQuery API. 1 . • • Both contain the exact same API.OxygenBlast .Intertech. the only difference is in size & formatting. Inc. and the content has been compressed. 2009 • www.Understanding jQuery • As noted in the previous image. Copyright © Intertech. most white space and comments have been removed.To produce the smallest file possible.Production Version .

• Their names suggest the proper usage for each version. Copyright © Intertech. 2009 • www.Understanding jQuery • 2 .OxygenBlast .Development Version .com • 800-866-9884 • Slide 10 . the production version is the one you should use in your “live” Ajax applications. including white-space for formatting and comments in the code.This is a “human readable” version of the API. • Due to the smaller file size. Inc.Intertech.

add it to your web content folder.w3.org/1999/xhtml' xml:lang='en'> <head> <title>Intertech jQuery Demo</title> <script type='text/javascript' src='jquery-1..org/TR/2002/REC-xhtml1-20020801/DTD/xhtml1-transitional. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.Intertech.js'> </script> </head> .2.dtd"> <html xmlns='http://www.w3.Understanding jQuery • After downloading the jQuery API JavaScript file of your choice..4.0 Transitional//EN" "http://www.min.com • 800-866-9884 • Slide 11 . • That‟s it! You are now ready to use jQuery! Copyright © Intertech. Inc.OxygenBlast . and use the <script> tag to link to it in your Web pages. 2009 • www.

Inc. 2009 • www. • A quick and common solution for solving the “cached resources” issue is to add a query string to the URL with a unique ID (most often a date/time stamp).” Cons .A client browser may have cached the included jQuery JavaScript file. thereby ignoring any updates you install. • Copyright © Intertech.com • 800-866-9884 • Slide 12 .2.js.Understanding jQuery • You may want to consider changing the name of the versioned jQuery file (such as “jquery-1. Simply download the latest version and change the file name to “jquery.OxygenBlast .You won‟t have to go into every Web page and update each jQuery link when you upgrade your version of the API. by using the System.” • Pros . so it does not cache the resource.currentTimeMillis() method.js.min. • There is no negative affect on the Web server. • This produces a unique URL as far as the browser is concerned.js”) to the more generic “jquery.4.Intertech. the unique ID is ignored. • Here‟s an example of adding a unique ID in a JSP.

w3..currentTimeMillis()%>'> </script> </head> .com • 800-866-9884 • Slide 13 .org/TR/2002/REC-xhtml1-20020801/DTD/xhtml1-transitional.js?<%= System. Inc.org/1999/xhtml' xml:lang='en'> <head> <title>Intertech jQuery Demo</title> <script type='text/javascript' src='jquery.0 Transitional//EN" "http://www. 2009 • www.Intertech..OxygenBlast . Copyright © Intertech.w3.Understanding jQuery <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.dtd"> <html xmlns='http://www.

but choosing “$” results in more compact code. • • There are two identifiers used to access this object: “$” and “jQuery” Either can be used. jQuery. Inc. you can release jQuery‟s hold on it by calling the “noConflict()” method: // Release the “$” identifier from jQuery $. // Both of these statement are equivalent to one another.Understanding jQuery • jQuery provides its functionality through a single object.someMethod().OxygenBlast . // Now the “jQuery” identifier is used instead of “$” jQuery. 2009 • www. function.someMethod().noConflict().someMethod(). • Resolving identifier conflicts: • If you have a situation where another variable.Intertech.com • 800-866-9884 • Slide 14 . $. Copyright © Intertech. or object also uses “$” as an identifier.

2009 • www. Copyright © Intertech. Inc.OxygenBlast . it‟s best to pick a single identifier and use it consistently. • This improves readability and maintenance.Intertech. // Now the “jq” identifier is used instead of “$” jq.someMethod().noConflict().Understanding jQuery • Creating your own identifier: • The noConflict() method returns a handle to the jQuery object. so you can also use this to create your own custom identifier. • Regardless of which strategy you choose. // Release the “$” identifier from jQuery and create one called “jq” var jq = $.com • 800-866-9884 • Slide 15 .

aMethod2().aMethod(). $. 2009 • www.aMethod(). $. your source code may contain repetitive use of the “$” identifier. • This allows method calls to be chained together without requiring the repetitive use of the jQuery identifier.OxygenBlast . most jQuery methods return a reference to itself.aMethod4())).Understanding jQuery • Since many jQuery actions are handled through the jQuery object. method chaining and nesting may produce code that is difficult to read. • As a best practice.$.anotherMethod(). $.Intertech.aMethod(42. $. Inc. $.anotherMethod(). Copyright © Intertech.yetAnotherMethod(). • To minimize this redundancy.aMethod3($.com • 800-866-9884 • Slide 16 .yetAnotherMethod().aMethod5(). favor clarity over minimizing redundancy • When combined.

.com • 800-866-9884 • Slide 17 .OxygenBlast .Intertech. element selection is executed through the DOM API: The most common method is to use document. Inc. 2009 • www.getElementById(<ID>).Understanding jQuery • You must first select an element on a Web page before reading or modifying it with your JavaScript code. </script> </head> <body> <input type=”text” id=”FirstName” name=”FirstName” /> </body> • Another common method is to locate the target node by using the DOM API to traverse the tree. • • In traditional JavaScript.getElementById(“FirstName”).. <head> <script> var customerElement = document. Copyright © Intertech. // .

firstChild.OxygenBlast . and Class.status == 200 ) { var xmlDOM = req.nodeType ). if( req.com • 800-866-9884 • Slide 18 .responseXML.getElementById( “customer” ). Copyright © Intertech. 2009 • www. • Recall that CSS primarily uses three types of selectors: Element. alert( xmlDOM.firstChild.Intertech. Inc. } } • jQuery simplifies this by implementing its selection API with a syntax based on Cascading Style Sheets (CSS). ID.readyState == 4 && req.Understanding jQuery function displayCustomerInfo( req ) { var customerElement = document.

Understanding jQuery • Consider the following example: <div id="employeeSearch"> Employee ID: <input class="employee" id="employeeID" name="employeeID" type="text" /><br /> Division ID: <input class="division" id="divisionID" name="divisionID" type="text" /><br /> </div> • CSS selectors to match elements on this page might look like this: <style> div#employeeSearch input {color: blue} /* Selects Both Input Tags */ #employeeID {background-color: white} /* Selects a Single Input Tag */ </style> Copyright © Intertech. Inc.Intertech. 2009 • www.com • 800-866-9884 • Slide 19 .OxygenBlast .

Copyright © Intertech. 2009 • www.com • 800-866-9884 • Slide 20 .Understanding jQuery • jQuery matches elements in exactly the same way. Inc.Intertech. otherwise it will not match any elements on the page. $("div#employeeSearch input") // Selects Both Input Tags $("#employeeID") // Selects a Single Input Tag • NOTE: Don‟t forget to surround your selector with quotes (single or double).OxygenBlast .

1.querySelectorAll( “selector” ) for multiple elements.OxygenBlast . and document. jQuery. 2009 • www.querySelector( “selector” ) for a single element. and so on) have implemented two methods to use this same CSS styled selection. Firefox 3.com • 800-866-9884 • Slide 21 . Inc. called “Sizzle” http://sizzlejs.Understanding jQuery • Recent versions of popular browsers (such as IE 8. the “jQuery Project” offers this selector API as a stand-alone library. however.Intertech. • • • document. In addition to being bundled with the core jQuery API.com/ Copyright © Intertech. provides this functionality with older browser versions as well.

Select all of the elements in the set with even indices (0. 2.. Inc. 5. 7.. Select all of the elements in the set that do not match the selector specified here.Intertech.OxygenBlast . A subset of the total elements matched can be accessed through a special selector. This process is known as “filtering. Select the first element in the set.com • 800-866-9884 • Slide 22 . 2009 • www. Select the last element in the set.. Select all of the elements in the set with odd indices (1. 3.). Select all of the elements in the set that are after the index specified.. 4. a selector may match a set of elements. starting with the number 0.Understanding jQuery • As shown in the preceding example. Select all of the elements in the set that are before the index specified. 6. Selector (Filtering) :eq( index ) :first :last :lt( index ) :gt( index ) :even :odd :not( selector ) :contains( text ) Copyright © Intertech.). Select all of the elements in the set that contains the case sensitive text specified here. • • Each element is given an index.” Definition Select the nth element in the set.

• This and other rendering methods are examined in detail in a later section of this seminar. Copyright © Intertech. Inc. 2009 • www.Understanding jQuery <body> <div id="Number0">Number 0</div> <div id="Number1Section">Number 1</div> <div id="SectionNumber2">Number 2</div> <div>This is Number 3</div> <div>Number 4</div> <div>Number 5</div> <div>This is Number 6</div> <div>Number 7</div> </body> • The css() method used in the examples below.OxygenBlast .Intertech.com • 800-866-9884 • Slide 23 . applies style definitions to each selected elements in the set.

"red").OxygenBlast . 2009 • www. Inc.Understanding jQuery • Equals: <body> <div id="Number0">Number 0</div> <div id="Number1Section">Number 1</div> <div id="SectionNumber2">Number 2</div> <div>This is Number 3</div> <div>Number 4</div> <div>Number 5</div> <div>This is Number 6</div> <div>Number 7</div> </body> $("div:eq(2)"). Copyright © Intertech.css("background-color".com • 800-866-9884 • Slide 24 .Intertech.

css("background-color". 2009 • www.OxygenBlast .com • 800-866-9884 • Slide 25 .Intertech. "red"). Inc. Copyright © Intertech.Understanding jQuery • Greater Than: <body> <div id="Number0">Number 0</div> <div id="Number1Section">Number 1</div> <div id="SectionNumber2">Number 2</div> <div>This is Number 3</div> <div>Number 4</div> <div>Number 5</div> <div>This is Number 6</div> <div>Number 7</div> </body> $("div:gt(3)").

Copyright © Intertech.css("background-color".com • 800-866-9884 • Slide 26 .Intertech. "red"). Inc.OxygenBlast . 2009 • www.Understanding jQuery • Odd: <body> <div id="Number0">Number 0</div> <div id="Number1Section">Number 1</div> <div id="SectionNumber2">Number 2</div> <div>This is Number 3</div> <div>Number 4</div> <div>Number 5</div> <div>This is Number 6</div> <div>Number 7</div> </body> $("div:odd").

OxygenBlast .com • 800-866-9884 • Slide 27 .css("background-color". Copyright © Intertech. Inc. "red"). 2009 • www.Understanding jQuery • Contains: <body> <div id="Number0">Number 0</div> <div id="Number1Section">Number 1</div> <div id="SectionNumber2">Number 2</div> <div>This is Number 3</div> <div>Number 4</div> <div>Number 5</div> <div>This is Number 6</div> <div>Number 7</div> </body> $("div:contains(This is)").Intertech.

Select all elements that match the element name and contain the attribute specified.OxygenBlast .Intertech. as long as the value of this attribute starts with the text specified. element[att-name = text] element[att-name ^= text] element[att-name $= text] element[att-name *= text] element[att-name != text] Select all elements that match the element name and contain the attribute specified. 2009 • www.Understanding jQuery • Element selection can be further refined by using an Attribute Selector Attribute Selector element[att-name] Definition Select all elements that match the element name and contain the attribute specified. Select all elements that match the element name and contain the attribute specified.com • 800-866-9884 • Slide 28 . Copyright © Intertech. Inc. as long as the value of this attribute contains the text specified. as long as the value of this attribute contains the text specified anywhere in the String. Select all elements that match the element name and contain the attribute specified. Select all elements that match the element name and contain the attribute specified. as long as the value of this attribute ends with the text specified. as long as the value of this attribute does not have the text specified.

"red").com • 800-866-9884 • Slide 29 .Understanding jQuery • Contains a named Attribute: <body> <div id="Number0">Number 0</div> <div id="Number1Section">Number 1</div> <div id="SectionNumber2">Number 2</div> <div>This is Number 3</div> <div>Number 4</div> <div>Number 5</div> <div>This is Number 6</div> <div>Number 7</div> </body> $("div[id]"). Inc. Copyright © Intertech.Intertech.OxygenBlast .css("background-color". 2009 • www.

css("background-color". 2009 • www. Inc.OxygenBlast . Copyright © Intertech. "red").Intertech.com • 800-866-9884 • Slide 30 .Understanding jQuery • Attribute value starts with „Number‟: <body> <div id="Number0">Number 0</div> <div id="Number1Section">Number 1</div> <div id="SectionNumber2">Number 2</div> <div>This is Number 3</div> <div>Number 4</div> <div>Number 5</div> <div>This is Number 6</div> <div>Number 7</div> </body> $("div[id ^= Number]").

com • 800-866-9884 • Slide 31 . "red").Intertech. Inc. 2009 • www.Understanding jQuery • Attribute value contains „Section‟: <body> <div id="Number0">Number 0</div> <div id="Number1Section">Number 1</div> <div id="SectionNumber2">Number 2</div> <div>This is Number 3</div> <div>Number 4</div> <div>Number 5</div> <div>This is Number 6</div> <div>Number 7</div> </body> $("div[id *= Section]"). Copyright © Intertech.css("background-color".OxygenBlast .

com • 800-866-9884 • Slide 32 . the framework executes the iteration for you. Inc.” • • • Any method that is called upon a selection with multiple elements has that method called upon all of the elements in the set.Understanding jQuery • Besides offering a rich and compact selector API. 2009 • www.Intertech. Therefore. A traditional JavaScript example: Copyright © Intertech. jQuery reduces the amount of code necessary by providing “Implicit Iteration.OxygenBlast . there is no need to write code for looping.

item( i ).length. i < employeeArray.item(i).item(i). "blue" ).OxygenBlast .com • 800-866-9884 • Slide 33 . 2009 • www.nodeName == “div” && employeeArray. Copyright © Intertech.color = "blue".getElementById("employeeSearch").Intertech.hasAttribute("id") ) { if( employeeArray. i++ ) { if( employeeArray.item(i).Understanding jQuery var employeeArray = document.css( "color". Inc.getAttribute("id") != "number3" ) { employeeArray.style. for( i = 0.childNodes. } } } • jQuery reduces the previous block of code to one short line: $( "div#employeeSearch div:not(#number3)" ).

2009 • www. Copyright © Intertech.OxygenBlast .com • 800-866-9884 • Slide 34 . • jQuery‟s methods for retrieving data and handing events facilitate organization as well as reduce the amount of code that needs to be written.Intertech.Understanding jQuery • jQuery‟s Ajax utilities greatly reduce the amount of code that needs to be written. Inc.

Intertech.com • 800-866-9884 • Slide 35 . Copyright © Intertech. ultimately being displayed in a <div> element. Inc. 2009 • www. • An XHTML page calls a JavaScript function once a button is pushed. <body> Username: <input type="text" name="username" id="username" /> <button onclick="submitUsername()">Submit</button><br /> <div id="status"></div> </body> • The JavaScript function creates an Ajax request and a callback function handles the response.Understanding jQuery • Consider a typical Ajax example. where some data needs to be retrieved from a server.OxygenBlast .

com • 800-866-9884 • Slide 36 .open( httpMethod. var req = getXMLHttpRequest(). req. } function displayStatus(req) { if( req.value.OxygenBlast .getElementById( "username" ). } } function getXMLHttpRequest() { // Custom method to create a browser specific request.getElementById( "status" ).innerHTML = req.onreadystatechange = function() { displayStatus( req ) }. url. var isAsynchronousRequest = true. 2009 • www.send( null ).Understanding jQuery function submitUsername() { var username = document. isAsynchronousRequest ).Intertech. Inc.readyState == 4 && req. req. } Copyright © Intertech. statusElement. var httpMethod = "GET". var url = "StatusVerifier?username=" + escape( username ).status == 200 ) { var statusElement = document.responseText. req.

Page Not Found). through the load() method.load( "StatusVerifier?username=“ + escape( $("#username").com • 800-866-9884 • Slide 37 .this function is called even if the request is unsuccessful (such as a 404 . } • The val() method retrieves the value of the element (similar to the “value” property in the DOM API).Understanding jQuery • jQuery provides a much simpler way to retrieve and place data directly into an element.val() ) ).Intertech. • 2 . 2009 • www. function submitUsername() { $("#status"). • This method is attached to an element and takes two parameters: • 1 .OxygenBlast . NOTE .[OPTIONAL] A callback function that is executed after the request has been completed.The URL to send the request to. Copyright © Intertech. Inc.

a callback function must handle any response processing and page rendering. Another difference between these two and load() is the callback function is NOT executed if the request is unsuccessful (such as a 404 error). a better way to attach handlers to elements is explored. Unlike load().get() . Inc.Intertech.” In the “event handler” section of this seminar. there are two additional jQuery methods: • • • • $.executes an HTTP POST request. the HTTP status. $. 2009 • www.executes an HTTP GET request.post() . Do More. • For more complex scenarios. there is no need to create a browser specific XMLHttpRequest.com • 800-866-9884 • Slide 38 .Understanding jQuery • • • When using load().OxygenBlast . check the readyState. where a callback function needs to process the response. these methods are not attached to an element. Copyright © Intertech. nor provide a callback function. This is another example of jQuery staying true to its motto: “Write Less.

OxygenBlast . strongElm. and so on).appendChild( strongElm ).Intertech. var strongElm = document. </script> Copyright © Intertech. 2009 • www. Inc.createElement("strong"). 2 .Understanding jQuery • A typical DOM API scenario for adding a set of new elements to a Web page.appendChild( greetingText ). var greetingText = document.Assemble the nodes into a tree structure 3 .Create each node needed (elements. attributes.com • 800-866-9884 • Slide 39 .createElement("div").Add the parent node to an existing element on the Web page // Steps 1 & 2 <script> var greetingDiv = document.createTextNode("Hellooooooo!"). text. greetingDiv. required several steps: • • • 1 .

com • 800-866-9884 • Slide 40 .Intertech. 2009 • www. Copyright © Intertech.Understanding jQuery • jQuery simplifies by this by providing a syntax to create all of the nodes in the tree at the same time: $('<div><strong>Hellooooooo!</strong></div>').OxygenBlast . Inc.

after( <B> ) Definition Add 1 or more attributes by using a JSON name/value syntax. <A>.removeAttr( <attr-name> ) <A>. Add <A> as the first child to all elements that match <B> Add <B> as the first child to all elements selected with <A> Add <A> as the last child to all elements that match <B> Add <A> as the last child to all elements that match <B> Add <A> as a sibling immediately before all elements that match <B> Add <B> as a sibling immediately before all elements selected with <A> Add <A> as a sibling immediately after all elements that match <B> Add <B> as a sibling immediately after all elements selected with <A> Copyright © Intertech.insertAfter( <B> ) <A>.before( <B> ) <A>.appendTo( <B> ) A. Inc. 2009 • www.prependTo( <B> ) A.insertBefore( <B> ) <A>. <A>.append( B ). Remove an attribute that matches the name passed into this method.Understanding jQuery • jQuery provides several different DOM manipulation methods (such as adding and removing attributes.OxygenBlast .attr( <JSON> ) .Intertech. as well as arranging nodes in a tree).com • 800-866-9884 • Slide 41 .prepend( B ). DOM Methods .

OxygenBlast . (Type 3: Text) Copyright © Intertech.. </div> </div> div ID = “mainDiv” (Type 1: Element) Some Text. (Type 3: Text) div ID = “anotherDiv” (Type 1: Element) More Text... 2009 • www... Inc. <div id="anotherDiv"> More text.com • 800-866-9884 • Slide 42 ..Understanding jQuery • The following DOM examples are applied to this block of XHTML: <div id="mainDiv"> Some Text..Intertech..

.com • 800-866-9884 • Slide 43 . Inc.OxygenBlast . (Type 3: Text) div ID = “anotherDiv” (Type 1: Element) This is New! (Type 3: Text) More Text. (Type 3: Text) Copyright © Intertech..Intertech.prependTo('div#mainDiv'). // prepend $('div#mainDiv'). 2009 • www. div ID = “mainDiv” (Type 1: Element) div ID = “newDiv” (Type 1: Element) Some Text..Understanding jQuery • prependTo & prepend: // prependTo $('<div id=”newDiv”> This is New! </div>').prepend('<div id=”newDiv”> This is New! </div>')..

Intertech. Inc..appendTo('div#mainDiv').append('<div id=”newDiv”> This is New! </div>'). // append $('div#mainDiv')..Understanding jQuery • appendTo & append: // appendTo $('<div id=”newDiv”> This is New! </div>'). (Type 3: Text) This is New! (Type 3: Text) Copyright © Intertech. (Type 3: Text) div ID = “anotherDiv” (Type 1: Element) div ID = “newDiv” (Type 1: Element) More Text.com • 800-866-9884 • Slide 44 ..OxygenBlast .. div ID = “mainDiv” (Type 1: Element) Some Text. 2009 • www.

div ID = “mainDiv” (Type 1: Element) Some Text. (Type 3: Text) div ID = “newDiv” (Type 1: Element) div ID = “anotherDiv” (Type 1: Element) This is New! (Type 3: Text) More Text..Intertech.OxygenBlast .. (Type 3: Text) Copyright © Intertech..insertBefore('div#anotherDiv'). 2009 • www.Understanding jQuery • insertBefore & before: // insertBefore $('<div id=”newDiv”> This is New! </div>').com • 800-866-9884 • Slide 45 . Inc. // before $('div#anotherDiv').before('<div id=”newDiv”> This is New! </div>')..

Set an event handler property on an HTMLElement object.Understanding jQuery • Event handlers are programmatically added to elements in two different ways. 2009 • www. • 2 . Copyright © Intertech.OxygenBlast .getElementById(“StockButton”).Intertech. • 1 .Use browser specific methods to attach an event handler to an HTMLElement object. but your code must branch for each supported browser. • While this is cross-browser compliant.onclick = loadNewStockQuote. Inc. it only allows a single event handler per event type.com • 800-866-9884 • Slide 46 . document. • This allows multiple handlers to be attached to a single event type.

// stopPropagation).getElementById(“StockButton”). false). changeStockImage).getElementById(“StockButton”). document.Understanding jQuery // In IE: attachEvent( eventType. false).OxygenBlast .com • 800-866-9884 • Slide 47 . document.getElementById(“StockButton”). document.attachEvent(“onmouseover”. eventHandler.getElementById(“StockButton”). 2009 • www.attachEvent(“onclick”. changeStockImage. // In Mozilla: addEventListener( eventType. loadNewStockQuote. loadNewStockQuote).addEventListener(“click”. Copyright © Intertech.Intertech.addEventListener(“mouseover”. document. Inc. eventHandler ).

addEventListener( "load". window. for code which should only be executed once the page has been completed loaded. init ). // This syntax only allows one handler for the onload event. // Multiple onload handlers for Mozilla window. window. if a function is called before the page is loaded. 2009 • www. init2 ).OxygenBlast .. // Multiple onload handlers for IE window.Intertech.. window. false ). init2.attachEvent( "onload".addEventListener( "load".com • 800-866-9884 • Slide 48 ..} Copyright © Intertech. Inc. false ). init. it is possible that the elements and resources they are attempting to read or manipulate may not be available.onload = init. • Otherwise.Understanding jQuery • The most basic event that concerns JavaScript developers is “window.onload” • Developers attach handlers to this event. } function init2() { // .attachEvent( "onload".. function init() { //.

Copyright © Intertech. $("document").com • 800-866-9884 • Slide 49 . Inc. anotherInit().ready( function() { init(). 2009 • www.ready( function() { anotherInit().OxygenBlast .Intertech. } ). } ).Understanding jQuery • jQuery uses a different syntax to attach handlers to the onload event: $("document"). } ).ready( function() { init(). // or $("document").

2009 • www.OxygenBlast .com • 800-866-9884 • Slide 50 . . • Some use an identifier that match an event type (such as .Intertech. Copyright © Intertech.Understanding jQuery • jQuery provides several other methods to configure event handlers. and so on). • Like the event handler property of the HTMLElement object. Inc. these methods only allow a single handler per event type.focus().click().

onload waits for all resources (such as external images) to be loaded.It is faster than window.OxygenBlast . 2 .com • 800-866-9884 • Slide 51 . Inc.It can be called multiple times to add as many handlers as needed. 3 . • ready() only waits for the markup and scripts to be loaded before firing the event.The same ready() method is called for all supported browsers.Understanding jQuery • This syntax provides three advantages: • • • 1 . before firing the event.onload. Copyright © Intertech. 2009 • www.Intertech. • window.

” Configures a handler for when an element loses its focus. 2009 • www. Inc.click( loadNewStockQuote ). which was previously placed over an element. has now moved outside of it.com • 800-866-9884 • Slide 52 .click( handler ) .change( handler ) Definition Configures a handler for when a mouse button is clicked. Copyright © Intertech. Configures a handler for when a mouse cursor. Configures a handler for when an element becomes “in focus. Configures a handler for when a value changes for an input element.Understanding jQuery Common Event Handlers .focus( handler ) . $(“#StockButton”).mouseover( handler ) . Configures a handler for when a mouse cursor is placed over an element. .Intertech.mouseout( handler ) Configures a handler for when a form is submitted.blur( handler ) .OxygenBlast .submit( handler ) .

Inc. 2009 • www. $("#StockButton").bind( "click". loadNewStockQuote ).name]”.bind( “type[. jQuery provides a bind() method.bind( "click".Intertech. $("#StockButton").Understanding jQuery • For adding multiple event handlers to a single event type.OxygenBlast . changeStockImage ). Common Event Handlers . handler ) Definition Configures a handler for the event type passed in as the first parameter. This method can be called repeatedly on an element (or set) to add multiple handlers. Copyright © Intertech.com • 800-866-9884 • Slide 53 .

Copyright © Intertech.”). loadNewStockQuote ). Inc. If an identifier is not used. 2009 • www.Understanding jQuery • In addition to permitting multiple handlers per event type.OxygenBlast .bind( "click".Without an identifier: $("#StockButton").unbind( "click" ). the bind() method takes an optional identifier parameter. • • • This identifier can be any name that you choose to use. $("#StockButton").com • 800-866-9884 • Slide 54 .bind( "click". // Removes both events $("#StockButton"). changeStockImage ). It is attached to the event type parameter following a period (“. and can be used to remove specific handlers (via the unbind() method). • Example #1 .Intertech. unbind() removes all attached handlers.

load". $("#StockButton").com • 800-866-9884 • Slide 55 . Inc.bind( "click. // Removes the loadNewStockQuote. changeStockImage ). $("#StockButton").change".With an identifier: $("#StockButton").load" ). 2009 • www.OxygenBlast .Understanding jQuery • Example #2 . Copyright © Intertech.unbind( "click.bind( "click.Intertech. loadNewStockQuote ). but leaves // the changeStockImage handler.

"color" : "white" } $("#greeting"). $("#greeting"). "white"). • This method allows a specific style property. 2009 • www.com • 800-866-9884 • Slide 56 . Inc.OxygenBlast .Intertech. // or var myStyles = { "background-color" : "red". $("#greeting").css("color". to be set for the element(s) it is called upon. Copyright © Intertech.css("background-color". "red"). or a JSON map of properties.Understanding jQuery • Earlier examples in this seminar introduced the css() method.css( myStyles ).

OxygenBlast . If they have been applied.Understanding jQuery • In addition there are several methods used to add and remove classes: Common Class Manipulation Definition Methods . If more than one class is to be added. separate each class name with a space. Copyright © Intertech. they are added. separate each class name with a space.removeClass( className(s) ) Removes a class from the selected elements. Adds or removes the specified classes to the selected elements. If more than one class is to be removed.toggleClass( className(s) ) . Inc. . they are removed.addClass( className(s) ) Adds a class to the selected elements. 2009 • www. If they haven‟t been applied. depending on whether or not the classes have already been applied.Intertech.com • 800-866-9884 • Slide 57 .

Intertech.com • 800-866-9884 • Slide 58 . Inc.OxygenBlast .Understanding jQuery • Here‟s an example of using toggleClass() Copyright © Intertech. 2009 • www.

} </script> .com • 800-866-9884 • Slide 59 .makeItRed { background-color: red.toggle". <body> <div id="mainDiv" class="makeItRed">Some Text</div><br /> <input id="toggle" type="button" value="ToggleStyle" / > </body> Copyright © Intertech.bind( "click.. color: white } . } ). } function toggleStyle() { $("#mainDiv").Intertech.. function init() { $("#toggle"). Inc. 2009 • www.toggleClass("invertStyle").Understanding jQuery <style> .OxygenBlast .invertStyle { background-color: white. color: red } </style> <script language="JavaScript"> $( "document " ).ready( function() { init(). toggleStyle ).

2009 • www. etc. a Web page might feature an image sliding down or slowly appearing into view. Inc. Copyright © Intertech.OxygenBlast .Understanding jQuery • CSS and JavaScript are used in combination to provide different types of effects on text. • For example. images.com • 800-866-9884 • Slide 60 .Intertech.

Hides the selected elements. [callback] ) .Understanding jQuery • jQuery provides simple utility methods for producing these common effects. Slides the selected elements down until they are in complete view.fadeTo( duration. [callback] ) .OxygenBlast .Intertech. which will be called once the effect has completed. and opacity increased until they are completely visible.slideUp( [duration]. • • All of the methods below taken an optional „duration‟ parameter. Fades the selected elements out of view.hide( [duration].fadeIn( [duration]. height. This is typically used with the hide() method. 2009 • www. opacity [callback] ) . Slides the selected elements up until they are no longer in view. Copyright © Intertech.show( [duration].slideDown( [duration]. the elements will have their width. If the duration parameter is included. which can be set to „fast‟ or „slow.fadeOut( [duration]. Fades the selected elements to a specific opacity level (a number between 0 and 1). [callback] ) . Definition Fades the selected elements into view. [callback] ) Displays the selected elements.‟ There is also an optional callback parameter. Inc. height. If the duration parameter is included.com • 800-866-9884 • Slide 61 . the elements will have their width. [callback] ) . Common Effect Methods . and opacity reduced until they are no longer visible. [callback] ) .

} ).. Inc.Understanding jQuery • An example of hide() and fadeIn(): <script language="JavaScript"> $("document"). 2009 • www. } </script> . <body> <div id="mainDiv" class="makeItRed">Some Text</div> </body> Copyright © Intertech.hide(). function init() { $("#mainDiv")..Intertech.OxygenBlast .com • 800-866-9884 • Slide 62 .fadeIn("slow").ready( function() { init().

Understanding jQuery • An example of slideUp(): <script language="JavaScript"> $("document").com • 800-866-9884 • Slide 63 .slide".slideUp("slow"). function init() { $("#toggle").Intertech. } function slideUp() { $("#mainDiv"). slideUp ). 2009 • www.ready( function() { init(). Inc.bind( "click. <body> <div id="mainDiv" class="makeItRed">Some Text</div><br /> <input id="toggle" type="button" value="Slide Up" /> </body> Copyright © Intertech.OxygenBlast .. } ).. } </script> .

Understanding jQuery • jQuery is an extensible framework allowing third parties to create utilities and widgets. • • One of the most popular collection of plug-ins is the jQuery UI Library Like the jQuery core. 2009 • www.Intertech. Inc.com • 800-866-9884 • Slide 64 . this is maintained by the “jQuery Project” Copyright © Intertech.OxygenBlast .

Understanding jQuery • The jQuery UI Library provides widgets.com • 800-866-9884 • Slide 65 .Intertech.OxygenBlast . Inc. • The download is found at http://jqueryui. • This creates the smallest and most efficient package while meeting the requirements for your project. and other effects. 2009 • www. themes. Copyright © Intertech. theme.com/ • The UI Library Web site lets you choose which resources (components. animations. and version) you need prior to downloading. • This library is not offered as part of the jQuery core and must be downloaded separately.

Intertech.OxygenBlast . 2009 • www. Inc. where includes a list of dependencies. navigate to the online documentation found at the jQuery UI Web site. Copyright © Intertech.com • 800-866-9884 • Slide 66 . • Each widget contains an “Overview” tab.Understanding jQuery • To find out which resources you need to include in the download.

Understanding jQuery • There are four types of components available: • • • • UI Core .Intertech.Behaviors such as “Draggable.Controls such as “Tabs. There are dozens of themes to choose from. Copyright © Intertech. or you have the option to create your own.” “shake.The base classes for all other UI plug-ins Interactions .” • In addition to choosing your components. 2009 • www.” Widgets .” “Progressbar.” and “highlight.” Droppable.com • 800-866-9884 • Slide 67 . Inc. you can also select predefined “themes” • • This provides a uniform look and feel to all of your components.” and “Datepicker” Effects .Animations such as “explode.OxygenBlast .” and “Sortable.

2009 • www.1.8.Intertech.Understanding jQuery • Once your components have been selected. check out the sample index. Images.js'></script> <script type='text/javascript„ src='js/jquery-ui-1.custom. Inc.min. Include links to the main jquery-ui CSS and JavaScript file • If in doubt regarding which files to link to. the jQuery UI Web site generates a zip file.2.html file included in the root directory of the zip file. and so on.min.css“ rel="stylesheet" /> <script type='text/javascript' src='jquery-1.4.8. CSS Files. Unzip this file and add the contents to your Web project directory.com • 800-866-9884 • Slide 68 . • • • This contains several folders that include JavaScript Files.1.custom. <link type="text/css“ href="css/pepper-grinder/jquery-ui-1.js'></script> Copyright © Intertech.OxygenBlast .

.Configure the element through JavaScript.Create an element on the page for the widget. } ). Inc.Intertech. • 1 . <body> <div id="reservationDate"> Select Reservation Date: <input id="datepicker" type="text" /> </div> </body> Copyright © Intertech. For example.com • 800-866-9884 • Slide 69 . • 2 .. the following code adds a date picker to a web page: • <script language=“JavaScript”> $("document").Understanding jQuery • The code for adding UI Library components is typically very simple. 2009 • www.OxygenBlast .datepicker().ready( function() { $("#datepicker"). </script> .

Inc.Understanding jQuery • Complete documentation and demos for the UI Library can be found at http://jqueryui.com • 800-866-9884 • Slide 70 .com/demos/ Copyright © Intertech.Intertech.OxygenBlast . 2009 • www.

com>. Sebastopol: O'Reilly. Inc. "jQuery: The Write Less. Beginning JavaScript and CSS Development with jQuery. Copyright © Intertech. "Learning jQuery".Intertech.jquery. and Yehuda Katz. 3/12/2010 <http://www. Jeremy.OxygenBlast . 2005. Cody. 2010. jQuery. Lindley. DOM Scripting: Web Design with JavaScript and the Document Object Model.com>. Berkeley: Apress. York. Richard. jQuery in Action. 2009. 2009. 4/08/2010 <http://www. jQuery. Greenwich: Manning.Understanding jQuery • • • • • • • Bibeault. JavaScript Library". Bear. jQuery Cookbook: Solutions & Examples for jQuery Developers. 3/12/2010 <http://www. Keith.com>.learningjquery.com • 800-866-9884 • Slide 71 .jqueryui. Second Edition. Do More. 2009 • www. “jQuery User Interface”. Wrox.

com LinkedIn – http://linkedin.Intertech.intertech.intertech.intertech.aspx Copyright © Intertech.Understanding jQuery • • • • • • • Blogs .intertech.OxygenBlast .com/UserGroups/JavaUserGroup.com/resource/default.http://twitter.com Facebook – http://facebook.com Twin Cities Java User Group http://www.aspx . and XML Resources http://www.NET.com/resource/briefings.aspx Oxygen Blast Events http://www.http://www.com • 800-866-9884 • Slide 72 .com/Blog/ Twitter . Java.intertech.intertech. Inc.intertech. 2009 • www.

OxygenBlast - Understanding jQuery

          

What is jQuery? jQuery Setup jQuery‟s Identifiers Method Chaining Selecting Elements Ajax Utilities DOM Creation and Manipulation Event Handling Adding Styles & Effects UI Library Overview jQuery Resources

Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 73

OxygenBlast - Understanding jQuery

• Intertech offers free:
• • • • • Content packed newsletters Podcasts through iTunes YouTube videos Free Oxygen Blast seminars Whitepapers and .pdf downloads

• For the above and special offers, register for the newsletter at the bottom of our homepage
Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 74

OxygenBlast - Understanding jQuery

Founded in 1991, Intertech offers a full training line-up:
• • • JEE, open source technologies .NET, SQL Server, SharePoint XML, Ajax

Delivery formats include:
• • • Instructor-led public and onsite Instructor-led night and virtual Self-paced study

Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 75

For advanced purchase customers, Intertech offers Elite Rewards™—call 651-994-8558 +23

Intertech. Inc.com • 800-866-9884 • Slide 76 .Understanding jQuery • In addition to training. 2009 • www. Intertech delivers consulting • Consulting is part of our brand: Instructors Who Consult | Consultants Who Teach • Give your project success with our consulting services • To learn more.OxygenBlast . contact us at 651-994-8558 +11 Copyright © Intertech.

An Intertech Course .

An Intertech Course .