• Save
Understanding jQuery
Upcoming SlideShare
Loading in...5
×
 

Understanding jQuery

on

  • 7,888 views

This is a slide deck on jQuery. Intertech offers a course on Ajax that includes jQuery. It is offered in a format for Java developers: http://www.intertech.com/Courses/Course.aspx?CourseID=99338. ...

This is a slide deck on jQuery. Intertech offers a course on Ajax that includes jQuery. It is offered in a format for Java developers: http://www.intertech.com/Courses/Course.aspx?CourseID=99338. It's also offered in a format for .NET developers: http://www.intertech.com/Courses/Course.aspx?CourseID=99329

Statistics

Views

Total Views
7,888
Views on SlideShare
7,869
Embed Views
19

Actions

Likes
16
Downloads
0
Comments
0

3 Embeds 19

http://www.softworkr.com 16
http://www.linkedin.com 2
http://softworkr.posterous.com 1

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Understanding jQuery Understanding jQuery Presentation Transcript

  • 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
  • OxygenBlast - Understanding jQuery • DOM Creation and Manipulation • Event Handling • Adding Styles & Effects • UI Library Overview • jQuery Resources • Questions Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 4
  • OxygenBlast - Understanding jQuery • Many of the prerequisites for this webinar are taught in our Complete Ajax courses. • Complete Ajax for Java: • Advanced JavaScript • HTTP • DOM API • Testing & Debugging • Security • We also offer a Complete Ajax for .NET course. Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 5
  • OxygenBlast - Understanding jQuery • jQuery, released in 2006, is an open-source JavaScript framework with a large number of widgets and 3rd party plug-ins. • Its primary focus is to ease the complexity of coding JavaScript and Ajax applications. • Their motto is “write less, do more.” • This framework is free and licensed under the MIT and GNU General Public License, Version 2. • Browser support includes Firefox 2.0+, IE 6+, Safari 3+, Opera 9+, and Chrome 1+. Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 6
  • OxygenBlast - Understanding jQuery • jQuery is arguably the most popular JavaScript framework available. • One stats Web site listed jQuery as “the most detected JavaScript library in use on the web” by a wide-margin. (July 2010 - http://trends.builtwith.com/javascript) • jQuery is used by Google, Microsoft, Dell, IBM, Amazon, NBC, among others. • jQuery was created by John Resig who currently leads the project‟s development team. • 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.org/team Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 7
  • OxygenBlast - Understanding jQuery • The entire core jQuery API is a single JavaScript file, found at http://www.jquery.com Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 8
  • OxygenBlast - Understanding jQuery • As noted in the previous image, there are two primary versions of the jQuery API. • Both contain the exact same API; the only difference is in size & formatting. • 1 - Production Version - To produce the smallest file possible, most white space and comments have been removed, and the content has been compressed. Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 9
  • OxygenBlast - Understanding jQuery • 2 - Development Version - This is a “human readable” version of the API, including white-space for formatting and comments in the code. • Their names suggest the proper usage for each version. • Due to the smaller file size, the production version is the one you should use in your “live” Ajax applications. Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 10
  • OxygenBlast - Understanding jQuery • After downloading the jQuery API JavaScript file of your choice, add it to your web content folder, and use the <script> tag to link to it in your Web pages. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/2002/REC-xhtml1-20020801/DTD/xhtml1-transitional.dtd"> <html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en'> <head> <title>Intertech jQuery Demo</title> <script type='text/javascript' src='jquery-1.4.2.min.js'> </script> </head> ... • That‟s it! You are now ready to use jQuery! Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 11
  • OxygenBlast - Understanding jQuery • You may want to consider changing the name of the versioned jQuery file (such as “jquery-1.4.2.min.js”) to the more generic “jquery.js.” • Pros - You won‟t have to go into every Web page and update each jQuery link when you upgrade your version of the API. Simply download the latest version and change the file name to “jquery.js.” • Cons - A client browser may have cached the included jQuery JavaScript file, thereby ignoring any updates you install. • 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). • This produces a unique URL as far as the browser is concerned, so it does not cache the resource. • There is no negative affect on the Web server; the unique ID is ignored. • Here‟s an example of adding a unique ID in a JSP, by using the System.currentTimeMillis() method. Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 12
  • OxygenBlast - Understanding jQuery <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/2002/REC-xhtml1-20020801/DTD/xhtml1-transitional.dtd"> <html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en'> <head> <title>Intertech jQuery Demo</title> <script type='text/javascript' src='jquery.js?<%= System.currentTimeMillis()%>'> </script> </head> ... Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 13
  • OxygenBlast - Understanding jQuery • jQuery provides its functionality through a single object. • There are two identifiers used to access this object: “$” and “jQuery” • Either can be used, but choosing “$” results in more compact code. // Both of these statement are equivalent to one another. $.someMethod(); jQuery.someMethod(); • Resolving identifier conflicts: • If you have a situation where another variable, function, or object also uses “$” as an identifier, you can release jQuery‟s hold on it by calling the “noConflict()” method: // Release the “$” identifier from jQuery $.noConflict(); // Now the “jQuery” identifier is used instead of “$” jQuery.someMethod(); Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 14
  • OxygenBlast - 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. // Release the “$” identifier from jQuery and create one called “jq” var jq = $.noConflict(); // Now the “jq” identifier is used instead of “$” jq.someMethod(); • Regardless of which strategy you choose, it‟s best to pick a single identifier and use it consistently. • This improves readability and maintenance. Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 15
  • OxygenBlast - Understanding jQuery • Since many jQuery actions are handled through the jQuery object, your source code may contain repetitive use of the “$” identifier. $.aMethod(); $.anotherMethod(); $.yetAnotherMethod(); • To minimize this redundancy, most jQuery methods return a reference to itself. • This allows method calls to be chained together without requiring the repetitive use of the jQuery identifier. $.aMethod().anotherMethod().yetAnotherMethod(); • As a best practice, favor clarity over minimizing redundancy • When combined, method chaining and nesting may produce code that is difficult to read. $.aMethod(42,$.aMethod2().aMethod3($.aMethod4())).aMethod5(); Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 16
  • OxygenBlast - Understanding jQuery • You must first select an element on a Web page before reading or modifying it with your JavaScript code. • In traditional JavaScript, element selection is executed through the DOM API: • The most common method is to use document.getElementById(<ID>). <head> <script> var customerElement = document.getElementById(“FirstName”); // ... </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. Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 17
  • OxygenBlast - Understanding jQuery function displayCustomerInfo( req ) { var customerElement = document.getElementById( “customer” ); if( req.readyState == 4 && req.status == 200 ) { var xmlDOM = req.responseXML; alert( xmlDOM.firstChild.firstChild.nodeType ); } } • jQuery simplifies this by implementing its selection API with a syntax based on Cascading Style Sheets (CSS). • Recall that CSS primarily uses three types of selectors: Element, ID, and Class. Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 18
  • OxygenBlast - 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. 2009 • www.Intertech.com • 800-866-9884 • Slide 19
  • OxygenBlast - Understanding jQuery • jQuery matches elements in exactly the same way. $("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); otherwise it will not match any elements on the page. Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 20
  • OxygenBlast - Understanding jQuery • Recent versions of popular browsers (such as IE 8, Firefox 3.1, and so on) have implemented two methods to use this same CSS styled selection. • document.querySelector( “selector” ) for a single element, and document.querySelectorAll( “selector” ) for multiple elements. • jQuery, however, provides this functionality with older browser versions as well. • In addition to being bundled with the core jQuery API, the “jQuery Project” offers this selector API as a stand-alone library, called “Sizzle” - http://sizzlejs.com/ Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 21
  • OxygenBlast - Understanding jQuery • As shown in the preceding example, a selector may match a set of elements. • Each element is given an index, starting with the number 0. • A subset of the total elements matched can be accessed through a special selector. This process is known as “filtering.” Selector (Filtering) Definition :eq( index ) Select the nth element in the set. :first Select the first element in the set. :last Select the last element in the set. :lt( index ) Select all of the elements in the set that are before the index specified. :gt( index ) Select all of the elements in the set that are after the index specified. :even Select all of the elements in the set with even indices (0, 2, 4, 6...). :odd Select all of the elements in the set with odd indices (1, 3, 5, 7...). :not( selector ) Select all of the elements in the set that do not match the selector specified here. :contains( text ) Select all of the elements in the set that contains the case sensitive text specified here. Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 22
  • OxygenBlast - 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, applies style definitions to each selected elements in the set. • This and other rendering methods are examined in detail in a later section of this seminar. Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 23
  • OxygenBlast - 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)").css("background-color", "red"); Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 24
  • OxygenBlast - 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)").css("background-color", "red"); Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 25
  • OxygenBlast - 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").css("background-color", "red"); Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 26
  • OxygenBlast - 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)").css("background-color", "red"); Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 27
  • OxygenBlast - Understanding jQuery • Element selection can be further refined by using an Attribute Selector Attribute Selector Definition element[att-name] Select all elements that match the element name and contain the attribute specified. element[att-name = text] Select all elements that match the element name and contain the attribute specified, as long as the value of this attribute contains the text specified. element[att-name ^= text] Select all elements that match the element name and contain the attribute specified, as long as the value of this attribute starts with the text specified. element[att-name $= text] 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. element[att-name *= text] Select all elements that match the element name and contain the attribute specified, as long as the value of this attribute contains the text specified anywhere in the String. element[att-name != text] Select all elements that match the element name and contain the attribute specified, as long as the value of this attribute does not have the text specified. Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 28
  • OxygenBlast - 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]").css("background-color", "red"); Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 29
  • OxygenBlast - 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]").css("background-color", "red"); Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 30
  • OxygenBlast - 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]").css("background-color", "red"); Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 31
  • OxygenBlast - Understanding jQuery • Besides offering a rich and compact selector API, jQuery reduces the amount of code necessary by providing “Implicit Iteration.” • Any method that is called upon a selection with multiple elements has that method called upon all of the elements in the set. • Therefore, there is no need to write code for looping; the framework executes the iteration for you. • A traditional JavaScript example: Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 32
  • OxygenBlast - Understanding jQuery var employeeArray = document.getElementById("employeeSearch").childNodes; for( i = 0; i < employeeArray.length; i++ ) { if( employeeArray.item(i).nodeName == “div” && employeeArray.item(i).hasAttribute("id") ) { if( employeeArray.item(i).getAttribute("id") != "number3" ) { employeeArray.item( i ).style.color = "blue"; } } } • jQuery reduces the previous block of code to one short line: $( "div#employeeSearch div:not(#number3)" ).css( "color", "blue" ); Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 33
  • OxygenBlast - Understanding jQuery • jQuery‟s Ajax utilities greatly reduce the amount of code that needs to be written. • jQuery‟s methods for retrieving data and handing events facilitate organization as well as reduce the amount of code that needs to be written. Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 34
  • OxygenBlast - Understanding jQuery • Consider a typical Ajax example, where some data needs to be retrieved from a server, ultimately being displayed in a <div> element. • 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. Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 35
  • OxygenBlast - Understanding jQuery function submitUsername() { var username = document.getElementById( "username" ).value; var url = "StatusVerifier?username=" + escape( username ); var httpMethod = "GET"; var isAsynchronousRequest = true; var req = getXMLHttpRequest(); req.open( httpMethod, url, isAsynchronousRequest ); req.onreadystatechange = function() { displayStatus( req ) }; req.send( null ); } function displayStatus(req) { if( req.readyState == 4 && req.status == 200 ) { var statusElement = document.getElementById( "status" ); statusElement.innerHTML = req.responseText; } } function getXMLHttpRequest() { // Custom method to create a browser specific request. } Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 36
  • OxygenBlast - Understanding jQuery • jQuery provides a much simpler way to retrieve and place data directly into an element, through the load() method. • This method is attached to an element and takes two parameters: • 1 - The URL to send the request to. • 2 - [OPTIONAL] A callback function that is executed after the request has been completed. NOTE - this function is called even if the request is unsuccessful (such as a 404 - Page Not Found). function submitUsername() { $("#status").load( "StatusVerifier?username=“ + escape( $("#username").val() ) ); } • The val() method retrieves the value of the element (similar to the “value” property in the DOM API). Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 37
  • OxygenBlast - Understanding jQuery • When using load(), there is no need to create a browser specific XMLHttpRequest, check the readyState, the HTTP status, nor provide a callback function. • This is another example of jQuery staying true to its motto: “Write Less, Do More.” • In the “event handler” section of this seminar, a better way to attach handlers to elements is explored. • For more complex scenarios, where a callback function needs to process the response, there are two additional jQuery methods: • $.get() - executes an HTTP GET request. • $.post() - executes an HTTP POST request. • Unlike load(), these methods are not attached to an element; 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). Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 38
  • OxygenBlast - Understanding jQuery • A typical DOM API scenario for adding a set of new elements to a Web page, required several steps: • 1 - Create each node needed (elements, text, attributes, and so on). • 2 - Assemble the nodes into a tree structure • 3 - Add the parent node to an existing element on the Web page // Steps 1 & 2 <script> var greetingDiv = document.createElement("div"); var strongElm = document.createElement("strong"); var greetingText = document.createTextNode("Hellooooooo!"); strongElm.appendChild( greetingText ); greetingDiv.appendChild( strongElm ); </script> Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 39
  • OxygenBlast - 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>'); Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 40
  • OxygenBlast - Understanding jQuery • jQuery provides several different DOM manipulation methods (such as adding and removing attributes, as well as arranging nodes in a tree). DOM Methods Definition .attr( <JSON> ) Add 1 or more attributes by using a JSON name/value syntax. .removeAttr( <attr-name> ) Remove an attribute that matches the name passed into this method. <A>.prependTo( <B> ) Add <A> as the first child to all elements that match <B> A.prepend( B ); Add <B> as the first child to all elements selected with <A> <A>.appendTo( <B> ) Add <A> as the last child to all elements that match <B> A.append( B ); Add <A> as the last child to all elements that match <B> <A>.insertBefore( <B> ) Add <A> as a sibling immediately before all elements that match <B> <A>.before( <B> ) Add <B> as a sibling immediately before all elements selected with <A> <A>.insertAfter( <B> ) Add <A> as a sibling immediately after all elements that match <B> <A>.after( <B> ) Add <B> as a sibling immediately after all elements selected with <A> Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 41
  • OxygenBlast - Understanding jQuery • The following DOM examples are applied to this block of XHTML: <div id="mainDiv"> Some Text... <div id="anotherDiv"> More text... </div> </div> div ID = “mainDiv” (Type 1: Element) div Some Text... ID = “anotherDiv” (Type 3: Text) (Type 1: Element) More Text... (Type 3: Text) Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 42
  • OxygenBlast - Understanding jQuery • prependTo & prepend: // prependTo $('<div id=”newDiv”> This is New! </div>').prependTo('div#mainDiv'); // prepend $('div#mainDiv').prepend('<div id=”newDiv”> This is New! </div>'); div ID = “mainDiv” (Type 1: Element) div div Some Text... ID = “newDiv” ID = “anotherDiv” (Type 3: Text) (Type 1: Element) (Type 1: Element) This is New! More Text... (Type 3: Text) (Type 3: Text) Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 43
  • OxygenBlast - Understanding jQuery • appendTo & append: // appendTo $('<div id=”newDiv”> This is New! </div>').appendTo('div#mainDiv'); // append $('div#mainDiv').append('<div id=”newDiv”> This is New! </div>'); div ID = “mainDiv” (Type 1: Element) div div Some Text... ID = “anotherDiv” ID = “newDiv” (Type 3: Text) (Type 1: Element) (Type 1: Element) More Text... This is New! (Type 3: Text) (Type 3: Text) Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 44
  • OxygenBlast - Understanding jQuery • insertBefore & before: // insertBefore $('<div id=”newDiv”> This is New! </div>').insertBefore('div#anotherDiv'); // before $('div#anotherDiv').before('<div id=”newDiv”> This is New! </div>'); div ID = “mainDiv” (Type 1: Element) div div Some Text... ID = “newDiv” ID = “anotherDiv” (Type 3: Text) (Type 1: Element) (Type 1: Element) This is New! More Text... (Type 3: Text) (Type 3: Text) Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 45
  • OxygenBlast - Understanding jQuery • Event handlers are programmatically added to elements in two different ways. • 1 - Set an event handler property on an HTMLElement object. • While this is cross-browser compliant, it only allows a single event handler per event type. document.getElementById(“StockButton”).onclick = loadNewStockQuote; • 2 - Use browser specific methods to attach an event handler to an HTMLElement object. • This allows multiple handlers to be attached to a single event type, but your code must branch for each supported browser. Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 46
  • OxygenBlast - Understanding jQuery // In IE: attachEvent( eventType, eventHandler ); document.getElementById(“StockButton”).attachEvent(“onclick”, loadNewStockQuote); document.getElementById(“StockButton”).attachEvent(“onmouseover”, changeStockImage); // In Mozilla: addEventListener( eventType, eventHandler, // stopPropagation); document.getElementById(“StockButton”).addEventListener(“click”, loadNewStockQuote, false); document.getElementById(“StockButton”).addEventListener(“mouseover”, changeStockImage, false); Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 47
  • OxygenBlast - Understanding jQuery • The most basic event that concerns JavaScript developers is “window.onload” • Developers attach handlers to this event, for code which should only be executed once the page has been completed loaded. • Otherwise, if a function is called before the page is loaded, it is possible that the elements and resources they are attempting to read or manipulate may not be available. // This syntax only allows one handler for the onload event. window.onload = init; // Multiple onload handlers for IE window.attachEvent( "onload", init ); window.attachEvent( "onload", init2 ); // Multiple onload handlers for Mozilla window.addEventListener( "load", init, false ); window.addEventListener( "load", init2, false ); function init() { //... } function init2() { // ...} Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 48
  • OxygenBlast - Understanding jQuery • jQuery uses a different syntax to attach handlers to the onload event: $("document").ready( function() { init(); anotherInit(); } ); // or $("document").ready( function() { init(); } ); $("document").ready( function() { anotherInit(); } ); Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 49
  • OxygenBlast - Understanding jQuery • jQuery provides several other methods to configure event handlers. • Some use an identifier that match an event type (such as .click(), .focus(), and so on). • Like the event handler property of the HTMLElement object, these methods only allow a single handler per event type. Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 50
  • OxygenBlast - Understanding jQuery • This syntax provides three advantages: • 1 - The same ready() method is called for all supported browsers. • 2 - It can be called multiple times to add as many handlers as needed. • 3 - It is faster than window.onload. • window.onload waits for all resources (such as external images) to be loaded, before firing the event. • ready() only waits for the markup and scripts to be loaded before firing the event. Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 51
  • OxygenBlast - Understanding jQuery Common Event Definition Handlers .click( handler ) Configures a handler for when a mouse button is clicked. .change( handler ) Configures a handler for when a value changes for an input element. .submit( handler ) Configures a handler for when a form is submitted. .focus( handler ) Configures a handler for when an element becomes “in focus.” .blur( handler ) Configures a handler for when an element loses its focus. .mouseover( handler ) Configures a handler for when a mouse cursor is placed over an element. .mouseout( handler ) Configures a handler for when a mouse cursor, which was previously placed over an element, has now moved outside of it. $(“#StockButton”).click( loadNewStockQuote ); Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 52
  • OxygenBlast - Understanding jQuery • For adding multiple event handlers to a single event type, jQuery provides a bind() method. Common Event Definition Handlers .bind( “type[.name]”, Configures a handler for the event type passed in as the handler ) first parameter. This method can be called repeatedly on an element (or set) to add multiple handlers. $("#StockButton").bind( "click", loadNewStockQuote ); $("#StockButton").bind( "click", changeStockImage ); Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 53
  • OxygenBlast - Understanding jQuery • In addition to permitting multiple handlers per event type, the bind() method takes an optional identifier parameter. • This identifier can be any name that you choose to use. • It is attached to the event type parameter following a period (“.”), and can be used to remove specific handlers (via the unbind() method). • If an identifier is not used, unbind() removes all attached handlers. • Example #1 - Without an identifier: $("#StockButton").bind( "click", loadNewStockQuote ); $("#StockButton").bind( "click", changeStockImage ); // Removes both events $("#StockButton").unbind( "click" ); Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 54
  • OxygenBlast - Understanding jQuery • Example #2 - With an identifier: $("#StockButton").bind( "click.load", loadNewStockQuote ); $("#StockButton").bind( "click.change", changeStockImage ); // Removes the loadNewStockQuote, but leaves // the changeStockImage handler. $("#StockButton").unbind( "click.load" ); Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 55
  • OxygenBlast - Understanding jQuery • Earlier examples in this seminar introduced the css() method. • This method allows a specific style property, or a JSON map of properties, to be set for the element(s) it is called upon. $("#greeting").css("background-color", "red"); $("#greeting").css("color", "white"); // or var myStyles = { "background-color" : "red", "color" : "white" } $("#greeting").css( myStyles ); Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 56
  • OxygenBlast - Understanding jQuery • In addition there are several methods used to add and remove classes: Common Class Manipulation Definition Methods .addClass( className(s) ) Adds a class to the selected elements. If more than one class is to be added, separate each class name with a space. .removeClass( className(s) ) Removes a class from the selected elements. If more than one class is to be removed, separate each class name with a space. .toggleClass( className(s) ) Adds or removes the specified classes to the selected elements, depending on whether or not the classes have already been applied. If they haven‟t been applied, they are added. If they have been applied, they are removed. Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 57
  • OxygenBlast - Understanding jQuery • Here‟s an example of using toggleClass() Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 58
  • OxygenBlast - Understanding jQuery <style> .makeItRed { background-color: red; color: white } .invertStyle { background-color: white; color: red } </style> <script language="JavaScript"> $( "document " ).ready( function() { init(); } ); function init() { $("#toggle").bind( "click.toggle", toggleStyle ); } function toggleStyle() { $("#mainDiv").toggleClass("invertStyle"); } </script> ... <body> <div id="mainDiv" class="makeItRed">Some Text</div><br /> <input id="toggle" type="button" value="ToggleStyle" / > </body> Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 59
  • OxygenBlast - Understanding jQuery • CSS and JavaScript are used in combination to provide different types of effects on text, images, etc. • For example, a Web page might feature an image sliding down or slowly appearing into view. Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 60
  • OxygenBlast - Understanding jQuery • jQuery provides simple utility methods for producing these common effects. • All of the methods below taken an optional „duration‟ parameter, which can be set to „fast‟ or „slow.‟ • There is also an optional callback parameter, which will be called once the effect has completed. Common Effect Methods Definition .fadeIn( [duration], [callback] ) Fades the selected elements into view. .fadeOut( [duration], [callback] ) Fades the selected elements out of view. .fadeTo( duration, opacity [callback] ) Fades the selected elements to a specific opacity level (a number between 0 and 1). .slideUp( [duration], [callback] ) Slides the selected elements up until they are no longer in view. .slideDown( [duration], [callback] ) Slides the selected elements down until they are in complete view. This is typically used with the hide() method. .hide( [duration], [callback] ) Hides the selected elements. If the duration parameter is included, the elements will have their width, height, and opacity reduced until they are no longer visible. .show( [duration], [callback] ) Displays the selected elements. If the duration parameter is included, the elements will have their width, height, and opacity increased until they are completely visible. Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 61
  • OxygenBlast - Understanding jQuery • An example of hide() and fadeIn(): <script language="JavaScript"> $("document").ready( function() { init(); } ); function init() { $("#mainDiv").hide().fadeIn("slow"); } </script> ... <body> <div id="mainDiv" class="makeItRed">Some Text</div> </body> Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 62
  • OxygenBlast - Understanding jQuery • An example of slideUp(): <script language="JavaScript"> $("document").ready( function() { init(); } ); function init() { $("#toggle").bind( "click.slide", slideUp ); } function slideUp() { $("#mainDiv").slideUp("slow"); } </script> ... <body> <div id="mainDiv" class="makeItRed">Some Text</div><br /> <input id="toggle" type="button" value="Slide Up" /> </body> Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 63
  • OxygenBlast - 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, this is maintained by the “jQuery Project” Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 64
  • OxygenBlast - Understanding jQuery • The jQuery UI Library provides widgets, themes, animations, and other effects. • This library is not offered as part of the jQuery core and must be downloaded separately. • The download is found at http://jqueryui.com/ • The UI Library Web site lets you choose which resources (components, theme, and version) you need prior to downloading. • This creates the smallest and most efficient package while meeting the requirements for your project. Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 65
  • OxygenBlast - Understanding jQuery • To find out which resources you need to include in the download, navigate to the online documentation found at the jQuery UI Web site. • Each widget contains an “Overview” tab, where includes a list of dependencies. Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 66
  • OxygenBlast - Understanding jQuery • There are four types of components available: • UI Core - The base classes for all other UI plug-ins • Interactions - Behaviors such as “Draggable,” Droppable,” and “Sortable.” • Widgets - Controls such as “Tabs,” “Progressbar,” and “Datepicker” • Effects - Animations such as “explode,” “shake,” and “highlight.” • In addition to choosing your components, you can also select pre- defined “themes” • This provides a uniform look and feel to all of your components. • There are dozens of themes to choose from, or you have the option to create your own. Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 67
  • OxygenBlast - Understanding jQuery • Once your components have been selected, the jQuery UI Web site generates a zip file. • This contains several folders that include JavaScript Files, CSS Files, Images, and so on. • Unzip this file and add the contents to your Web project directory. • Include links to the main jquery-ui CSS and JavaScript file • If in doubt regarding which files to link to, check out the sample index.html file included in the root directory of the zip file. <link type="text/css“ href="css/pepper-grinder/jquery-ui-1.8.1.custom.css“ rel="stylesheet" /> <script type='text/javascript' src='jquery-1.4.2.min.js'></script> <script type='text/javascript„ src='js/jquery-ui-1.8.1.custom.min.js'></script> Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 68
  • OxygenBlast - Understanding jQuery • The code for adding UI Library components is typically very simple. • 1 - Create an element on the page for the widget. • 2 - Configure the element through JavaScript. • For example, the following code adds a date picker to a web page: <script language=“JavaScript”> $("document").ready( function() { $("#datepicker").datepicker(); } ); </script> ... <body> <div id="reservationDate"> Select Reservation Date: <input id="datepicker" type="text" /> </div> </body> Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 69
  • OxygenBlast - Understanding jQuery • Complete documentation and demos for the UI Library can be found at http://jqueryui.com/demos/ Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 70
  • OxygenBlast - Understanding jQuery • Bibeault, Bear, and Yehuda Katz. jQuery in Action, Second Edition. Greenwich: Manning, 2010. • "jQuery: The Write Less, Do More, JavaScript Library". jQuery. 3/12/2010 <http://www.jquery.com>. • “jQuery User Interface”. jQuery. 3/12/2010 <http://www.jqueryui.com>. • Keith, Jeremy. DOM Scripting: Web Design with JavaScript and the Document Object Model. Berkeley: Apress, 2005. • "Learning jQuery". 4/08/2010 <http://www.learningjquery.com>. • Lindley, Cody. jQuery Cookbook: Solutions & Examples for jQuery Developers. Sebastopol: O'Reilly, 2009. • York, Richard. Beginning JavaScript and CSS Development with jQuery. Wrox, 2009. Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 71
  • OxygenBlast - Understanding jQuery • Blogs - http://www.intertech.com/Blog/ • Twitter - http://twitter.intertech.com • Facebook – http://facebook.intertech.com • LinkedIn – http://linkedin.intertech.com • Twin Cities Java User Group - http://www.intertech.com/UserGroups/JavaUserGroup.aspx • Oxygen Blast Events - http://www.intertech.com/resource/briefings.aspx • .NET, Java, and XML Resources - http://www.intertech.com/resource/default.aspx Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 72
  • 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 • For advanced purchase customers, Intertech offers Elite Rewards™—call 651-994-8558 +23 Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 75
  • OxygenBlast - Understanding jQuery • In addition to training, 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, contact us at 651-994-8558 +11 Copyright © Intertech, Inc. 2009 • www.Intertech.com • 800-866-9884 • Slide 76
  • An Intertech Course
  • An Intertech Course