Published on

JQuery Presentation

Published in: Education, Technology


  1. 1. jQuery<br />Writes less, Do More<br />Ch. Vishwa Mohan<br />Freelance Software Consultant &<br />Corporate Trainer<br />
  2. 2. Table of Contents<br />jQuery Introduction<br />jQuery Basics<br />jQuery Core<br />Events<br />Animation<br />AJAX<br />Plugins<br />
  3. 3. jQuery Introduction<br />
  4. 4. Evolution<br />
  5. 5. With AJAX . . .<br />JavaScript has become essential to current web page development, but.. <br />JavaScript is not a good language design.<br />JavaScript has become bloated<br /><ul><li>DOM Navigation
  6. 6. Browser differences</li></ul>Writing JavaScript code is tedious, time-consuming and error prone. <br />
  7. 7. Why you might want to use jQuery<br />jQuery makes writing Javascript much easier. <br /><ul><li>DOM Navigation (CSS-like syntax)
  8. 8. Apply methods to sets of DOM elements.
  9. 9. Builder model (chain method calls)
  10. 10. Extensible and there are tons of libraries
  11. 11. Handles most of browser differences so you don’t have to </li></ul>Server provides data<br />jQuery on client provides presentation. <br />Advantages of jQuery over JavaScript are: <br /><ul><li>Much easier to use.
  12. 12. Eliminates cross browser problems </li></li></ul><li>What is DOM ?<br />DOM is a standardized object model across different browsers. <br />The Document Object Model (DOM) is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML and XML documents. <br />Aspects of the DOM such as “Elements” may be addressed and manipulated within the syntax of the programming language in use. <br />
  13. 13. What is DOM ?<br />There are four levels of standardized Document Object Model (DOM):<br />Level 0<br />Level 1<br />Level 2<br />Level 3 <br />The DOM Level 2 combines both DOM Level 1 and 2. It provides methods to access and manipulate style sheet elements, and provides further access to page elements relating to XML. This Level 2 have six different recommendations: <br />DOM2 Core<br />DOM2 HTML<br />DOM2 Style/CSS<br />DOM2 Events<br />DOM2 Traversal and Range<br />DOM2 Views<br />
  14. 14. What is jQuery ?<br />jQuery is not a language, it is a well written Java Script code. <br />Fast and Concise. <br />Simplifies the interaction between HTML and Java Script. <br />It’s syntax is same as JavaScript Syntax. <br />jQuery helps, <br />Improve the performance of the application. <br />Develop most browser compatible web page. <br />Implement UI related critical functionality. <br />Fast<br />Extensible<br />Microsoft is shipping jQuery with Visual Studio. <br />jQuery supports intellisense in Visual Studio 2010 and with 2008 SP1. <br />You can download latest version (1.6.1) of jQuery library at http://docs.jquery.com/Downloading_jQuery<br />
  15. 15. Why jQuery ?<br />Lightweight : 31KB in size as per v1.6.1 (Minified and Gzipped)<br />CSS 1–3 Complaint <br />Cross Browser support<br /> (IE 6.0, Fire Fox 2, Safari 3.0+, Opera 9.0, Chrome)<br />jQuery allows you to elegantly (and efficiently) find and manipulate the HTML elements with minimum code. <br />jQuery commands can be chained together. <br />jQuery is “DOM Scripting”<br />Great CommunityPlugins<br />TutorialsTestCoverage<br />Open (free) licenseBooks<br />
  16. 16. Who’s using jQuery?<br />
  17. 17. jQuery Dominating <br />Google trends comparison of JS Framework in last 12 months. <br />
  18. 18. How to Embed jQuery in your Page<br />By assigning your jQuery script file to the “src” property of script tag. <br /><html> <br /> <head> <br /> <script src=“path/to/jquery-x.x.js"></script> <br /> <script> <br /> $(document).ready(function(){<br /> // Start here<br /> }); <br /> </script> <br /> </head> <br /> <body> … </body> <br /> </html> <br />To link jQuery remotely instead of hosting in your server:<br /> <script type="text/javascript“ src="http://ajax.googleapis.com/ajax/libs/ jquery/1.4.0/jquery.min.js?ver=1.4.0"></script><br />jQuery Code<br />
  19. 19. What jQuery Provides<br />Select DOM elements on a page. <br /><ul><li>Either one element or group of them.</li></ul>Set properties of DOM elements, in groups. <br />Creates, deletes, shows and hides DOM elements.<br />Defines event behavior on a page <br /><ul><li>Click, Mouse movement, Dynamic styles. Dynamic Content, Etc.,</li></ul>Animations<br />AJAX calls. <br />
  20. 20. jQuery Basics<br />
  21. 21. jQuery Philosophy<br />The below is the illustration of how jQuery works:<br />{<br />Find Some Elements<br />$(“div”).addClass(“xyz”);<br />}<br />Do something with them<br />jQuery Object<br />
  22. 22. Basic Example<br />The following is a simple basic jQuery example how it works: <br />Let us assume we have the following HTML and wants to select all paragraphs:<br /><body> <br /> <div><br /> <p>I m a paragraph 1</p> <br /> <p>I m a paragraph 2</p> <br /> </div><br /> <p>I m another paragraph</p> <br /></body> <br /><ul><li>To select all paragraphs, you can use following jQuery : $(“p”)
  23. 23. Add a class to all the paragraphs : $(“p”).addClass(“redStyle”);</li></li></ul><li>The jQuery Function<br />jQuery() = $()<br />$(function) The “Ready” handler<br />$(‘selector’) Element selector Expression<br />$(element) Specify element(s) directly<br />$(‘HTML’) HTML creation<br />$.function() Execute a jQuery function<br />$.fn.myfunc() { } Create jQuery function<br />
  24. 24. The Ready Function<br />With the help of jQuery ready() function, you can detect the state of readiness of your document to execute java script.<br />The code included inside $(document).ready() will only run once the page is ready for JavaScript code to execute. <br />$(document).ready(function() {<br /> console.log('ready!');<br /> });<br />Inside the ready function the script will be executed when DOM is ready.<br />You can also pass named function instead of anonymous function. <br />5 different ways to specify the ready function<br />jquery(document).ready(function(){…..};);<br />jquery().ready(function(){….};)<br />jquery(function(){ ….};)<br />jquery(dofunc);<br />$(dofunc);<br />
  25. 25. jQuery Core<br />
  26. 26. jQuery Selectors<br />jQuery offers a set of tools for matching set of elements in a document.<br />If you wish to use any of the meta-characters ( such as !"#$%&'()*+,./:; <=>? @[]^`{|}~ ) as a literal part of a name, you must escape the character with two backslashes: .<br /><ul><li>Ex: If you have an element with id="foo.bar", you can use selector $("#foo.bar").</li></ul>Some of the selector examples: <br /><ul><li>$(“*”); //Selects all elements.
  27. 27. $(“#elmtID”); //Selecting elements by ID. ID must be unique.
  28. 28. $(“div.myClass”); //Selecting elements by class name.
  29. 29. $(‘input[name=myName]’); //Selecting elements by attribute.
  30. 30. $(‘input[name$=myName]’); //Selecting elements it attribute ends with myName. </li></ul>Choosing the good selector can improve the performance of your selector. <br />To test whether the specified selection contain elements or not. <br />if ($('div.foo').length) { ... } //If no elements it returns 0 and evaluates false. <br />
  31. 31. jQuery Selectors<br />The jQuery library allows you to select elements in your XHTML by wrapping them in $(“ ”). This $ sign in a jQuery wrapper. <br />You can also use single quote to wrap the element.<br /><ul><li>$("div"); // selects all HTML div elements
  32. 32. $("#myElmtD"); // selects one HTML element with ID "myElement"
  33. 33. $(".myClass"); // selects HTML elements with class "myClass"
  34. 34. $("p#myElmtID"); // selects HTML paragraph element with ID "myElement"
  35. 35. $("ullia.navigation"); // selects anchors with class "navigation" that are nested in list items. </li></ul>jQuery also support the use of CSS selectors also. <br /><ul><li>$("p > a"); // selects anchors that are direct children of paragraphs
  36. 36. $("input[type=text]"); // selects inputs that have specified type
  37. 37. $("a:first"); // selects the first anchor on the page
  38. 38. $("p:odd"); // selects all odd numbered paragraphs
  39. 39. $("li:first-child"); // selects each list item that's the first child in its list</li></li></ul><li>jQuery Selectors<br />jQuery also allows the use of its own custom selectors: <br /><ul><li>$(":animated"); // Selects elements currently being animated
  40. 40. $(":button"); // Selects any button elements (inputs or buttons)
  41. 41. $(":radio"); // Selects radio buttons
  42. 42. $(":checkbox"); // Selects checkboxes
  43. 43. $(":checked"); // Selects checkboxes or radio buttons that are selected
  44. 44. $(":header"); // Selects header elements (h1, h2, h3, etc.)
  45. 45. $(":disabled"); // Selects disabled form elements. (Enabled also there)
  46. 46. $(":img"); // Select inputs with type=“image”.
  47. 47. $(":file"); // Select inputs with type=“file”.
  48. 48. $(":password"); // Select inputs with type=“password”.</li></li></ul><li>Selecting Elements Example<br />The below are some of selectors examples:<br /><ul><li>$(selector) //The below are examples of selectors.
  49. 49. $(‘#id’) id of element.
  50. 50. $(‘p’) tag name.
  51. 51. $(‘.class’) CSS class
  52. 52. $(‘p.class’) <p> elements having the CSS class
  53. 53. $(‘p:first’) $(‘p:last’) $(‘p:odd’) $(‘p:even’)
  54. 54. $(‘p:eq(2)’) gets the 2nd <p> element (1 based)
  55. 55. $(‘p’)[1] gets the 2nd <p> element (0 based)
  56. 56. $(‘p:nth-child(3)) gets the 3rd <p> element of the parent. n=even, odd too.
  57. 57. $(‘p:nth-child(5n+1)’) gets the 1st element after every 5th one
  58. 58. $(‘p a’) <a> elements, descended from a <p>
  59. 59. $(‘p>a’) <a> elements, direct child of a <p>
  60. 60. $(‘p+a’) <a> elements, directly following a <p>
  61. 61. $(‘p, a’) <p> and <a> elements
  62. 62. $(‘li:has(ul)’) <li> elements that have at least one <ul> descendent
  63. 63. $(‘:not(p)’) all elements but <p> elements
  64. 64. $(‘p:hidden’) only <p> elements that are hidden
  65. 65. $(‘p:empty’) <p> elements that have no child elements
  66. 66. $(‘img’[alt]) <img> elements having an alt attribute</li></li></ul><li>Selecting Elements Example cont..,<br />The below are some more selectors examples:<br /><ul><li>$(‘a’[href^=http://]) //Select <a> elmt with an href attribute starting with ‘http://’.
  67. 67. $(‘a’[href$=pdf]) //Select <a> elmt with an href attribute ending with pdf
  68. 68. $(‘a’[href*=ntpcug]) //Select <a> elmt with an href attribute containing ‘ntpcug”. </li></li></ul><li>Working with Attributes <br />The $fn.attr method acts as both a getter and setter. <br />The $.fn.attr as a setter can accept either a key and a value, or an object containing one or more key/value pairs.<br />$('a').attr('href', 'allMyHrefsAreTheSameNow.html'); //single attribute.<br />$('a').attr({ // Multiple attribues. <br />'title' : 'all titles are the same too!', <br />'href' : 'somethingNew.html' <br />});<br />The below example demonstrates the getting attribute href of the first <a> element in the document. <br />$('a').attr('href');<br />
  69. 69. jQuery Core Methods<br />Most of the jQuery methods are called on jQuery objects. These are said to be part of the $.fn namespace and are called as jQuery object methods. <br />There are several other methods that do not act on a selection, these are part of jQuery (i.e., $) namespace and are best thought of as core jQuery methods. <br />Methods in the $ namespace (or jQuery namespace) are called as utility methods and do not work with selections. <br />Some of the utility methods are:<br /><ul><li>$.trim();
  70. 70. $.each()
  71. 71. $.proxy() //Returns a function that will always run in the provided scope.
  72. 72. $.inArray() //Return a value’s index in an Array.
  73. 73. $.extend() //Change the properties of the first object using properties </li></ul> // of subsequent objects. <br />There are few cases the $.fn namespace and jQuery core name space methods have same name. (Eg: $.each and $.fn.each). <br />
  74. 74. Traversing Elements <br />Once you have a jQuery selection, you can find other elements using your selection as a starting point.<br />With the help of jQuery traversal methods you can move around DOM tree. The below are the few traversal methods defined in jQuery: <br /><ul><li>$('h1').next('p');
  75. 75. $('div:visible').parent();
  76. 76. $('input[name=first_name]').closest('form');
  77. 77. $('#myList').children();
  78. 78. $('li.selected').siblings();</li></ul>You can also iterate over a selection using $fn.each() function. <br />This function iterates over all elements in a selection. <br />The function receives the index of the current element and the DOM element itself as arguments<br />Inside the function, the DOM element is available as this by default. <br />$('#myListli').each(function(idx, el) { console.log('Element ' + idx + <br /> 'has the following html: ' + $(el).html() ); });<br />
  79. 79. Storing Selections<br />If you made a selection, that might need to make again you should save the selection in a variable rather then making it again (It improves performance).<br />var$allDivs = $('div'); <br /><ul><li>Here variable name begin with $ sign.
  80. 80. Here $ is another character there is no special meaning for it.
  81. 81. It is a convention and not mandatory.
  82. 82. Once you stored in variable you can call jQuery method on it.
  83. 83. Stored selections doesn’t update when the DOM changes. </li></ul>You can call methods on the selection. Methods have two different flavors getters and setters. Normally getter and setter methods will have same name. <br />$('h1').html(); //Getter return the html for first h1. <br />$('h1').html('hello world'); //The $.fn.html() method used as a setter.<br /><ul><li>Getters get the requested value only for the first element in the selection.
  84. 84. Setters affects all elements in a selection.
  85. 85. Setters return a jQuery object, allowing you to continue to call jQuery methods on your selection; getters return whatever they were asked to get. </li></li></ul><li>Useful jQuery Functions<br />The below are the some of the useful jQuery functions: <br /><ul><li>.each() iterate over the set
  86. 86. .size() number of elements in set
  87. 87. .end() reverts to the previous set
  88. 88. .get(n) get just the nth element (0 based)
  89. 89. .eq(n) get just the nth element (0 based) also .lt(n) & .gt(n)
  90. 90. .slice(n,m) gets only nth to (m-1)th elements
  91. 91. .not(‘p’) don’t include ‘p’ elements in set
  92. 92. .add(‘p’) add <p> elements to set
  93. 93. .remove() removes all the elements from the page DOM
  94. 94. .empty() removes the contents of all the elements
  95. 95. .filter(fn/sel) selects elements where the func returns true or sel
  96. 96. .find(selector) selects elements meeting the selector criteria
  97. 97. .parent() returns the parent of each element in set
  98. 98. .children() returns all the children of each element in set
  99. 99. .next() gets next element of each element in set
  100. 100. .prev() gets previous element of each element in set
  101. 101. .siblings() gets all the siblings of the current element</li></li></ul><li>Accessing & Manipulating CSS Class Names<br />jQuery allows you to easily add, remove, and toggle CSS classes. <br /><ul><li>$("div").addClass("content"); // adds class "content" to all <div> elements
  102. 102. $("div").removeClass("content"); // removes class "content" from all <div> elmts
  103. 103. $("div").toggleClass("content"); //toggle the class “content”</li></ul>You can also check to see if any of the selected element has particular class<br /><ul><li>$("#myElement").hasClass("content")</li></ul>The above jQuery function hasClass also use to check a set of elements (instead of just one), and the result would be “true” if any of the element containing the class. <br />
  104. 104. Manipulating CSS Styles<br />jQuery includes a handy way to get and set CSS properties of elements.<br />CSS properties that normally include a hyphen need to be camel cased in JavaScript. (Eg: CSS property font-size is expressed as fontSize in JavaScript).<br />$('h1').css('fontSize'); // returns a string such as “20px"<br />With jQuery, CSS style can be added: <br /><ul><li>$("p").css("width", "400px"); // adds a width to all paragraphs
  105. 105. $("#myElemt").css("color", "blue") // makes text color blue on element #myElemt
  106. 106. $("ul").css("border", "solid 1px #ccc") // adds a border to all lists
  107. 107. $(“h1").css(‘fontSize’, ‘100px’); // Setting an individual property.
  108. 108. $(“h1").css(‘fontSize’, ‘100px’, ‘color” : ‘red”); // Setting multiple properties. </li></ul>Instead of changing CSS styles via hardcode you can apply CSS class on elements. It is a better approach (No hard code). <br />var$h1 = $('h1'); <br />$h1.addClass(‘myClass'); //removeClass and toggleClass is also there.<br />You can also find any particular CSS class applied for a given element: <br />if ($h1.hasClass('myClass')) { ... }<br />
  109. 109. Adding, Removing & Appending Elements and Contents<br />jQuery, easily manipulates the group of elements including their contents<br /><ul><li>Get the HTML of any element (similar to innerHTML in JavaScript). The below code returns all HTML(including text) inside #myElement. </li></ul>varmyElementHTML = $("#myElement").html();<br /><ul><li>For the above you don’t’ want to access the HTML, but only want the text of an element, then use text() instead of html().</li></ul>varmyElementHTML = $("#myElement").text(); //Excludes HTML markup. <br /><ul><li>If you want to change the HTML or text content of specified element:</li></ul>$("#myElement").html("<p>This is the new content.</p>"); //Content is replaced.<br /> $("#myElement").text(“This is the new content. "); //Only text content is replaced. <br /><ul><li>To append content to element. (Add the content to end of existing)</li></ul> $("#myElement").append("<p>This is the new content.</p>"); <br /> $(“p").append("<p>This is the new content.</p>"); //Add to end of all paragraphs<br /><ul><li> jQuery also offers the use of the following commands: appendTo(), prepend(), before(), insertBefore(), after(), wrap() andinsertAfter(). </li></ul>$(‘#target’).before(‘<p>Inserted before #target</p>’); $(‘#target’).wrap(‘<div></div>’);<br />
  110. 110. Manipulating Elements<br />Once you’ve made a selection on the elements, you can change, move, remove and clone the elements. <br /><ul><li>Basically changing the element means manipulating DOM in some manner. But most commonly you can change inner HTML or attribute of an element.
  111. 111. When method acts as getters, generally only works with the first element in the selection, and they don’t return jQuery object, so you don’t chain additional methods to them. One notable exception is $fn.text;</li></ul>Some of the manipulating functions are:<br /><ul><li>$fn.html(); //Get or set the HTML contents. </li></ul>Eg : $('#myDiv p:first').html('New <strong>first</strong> paragraph!');<br /><ul><li>$fn.text(); //Get or set the text contents. HTML will be stripped.
  112. 112. $fn.attr(); //Get or set the value of the provided attribute.
  113. 113. $fn.val(); //Gets or sets the value of an form element.
  114. 114. $fn.width(); //Gets or sets the width in pixels of the first element in the // selection as an integer. Height is also there.
  115. 115. $fn.position(); //Only getter. Gets the position information. </li></li></ul><li>Moving, Copying Elements<br />There are many ways to move elements around the DOM. The below are some of the methods. <br /><ul><li>$fn.insertAfter(); //Places the selected element(s) after the element you //provided as argument.
  116. 116. $fn.after(); //Places the element provided as an argument after the //selected element.
  117. 117. $fn.insertBefore();
  118. 118. $fn.before();
  119. 119. $fn.appendTo();
  120. 120. $fn.append();
  121. 121. $fn.prependTo();
  122. 122. $fn.prepend(); </li></ul>The below is a simple jQuery code make the first list item the last list item. <br />var $li = $('#myListli:first').appendTo('#myList');<br />
  123. 123. Removing Elements<br />There are two ways to remove elements from the page. They are $.fn.removeand $.fn.detach. <br />The remove function will remove the selections from the page; while the method does returns the removed element(s). <br />The detach function will persist the data and events. <br />There is a one more function empty, it simply remove its contents but leaves the elements on the page. <br />
  124. 124. Creating new Elements<br />jQuery offers a trivial and elegant way to create new elements using the same $() method you use to make selections. <br />Eg:$('<p>This is a new paragraph</p>');<br />$('<li class="new">new list item</li>');<br />Creating a new element with an attribute object. <br />$('<a/>', {<br />html : 'This is a <strong>new</strong> link',<br />'class' : 'new',<br />href : 'foo.html‘ });<br /><ul><li>Able the attributes object we included as the second argument,
  125. 125. The property name class is quoted, while the property names text and href are not. Because property is quoted it is reserved word.(as class is in this case).</li></li></ul><li>Showing & Hiding Elements<br />The syntax for showing, hiding and toggling elements is given below: <br />$("#myElement").hide("slow", function() {<br /> // This code is executed once the element is hidden. <br />}<br />$("#myElement").show(“fast", function() {<br /> // This code is executed once the element is shown. <br />}<br />$("#myElement").toggle(1000, function() {<br /> // This code is executed once the element is shown or hidden. <br />}<br /> You can also make fade and element in or out. <br />$("#myElement").fadeOut("slow", function() { //Similarly fadeIn is there., <br /> }); // This function called when fadeOut is finished. <br />To fade an element only partially either in or out. <br /> $("#myElement").fadeTo(2000, 0.4, function() { }); // called when fade is finished.<br /><ul><li>The second parameter 0.4 is opacity. Similar to way opacity set in CSS. </li></li></ul><li>Animations and Effects<br />With the help of jQuery you can slide elements, animate elements and even stop animation in mid-sequence. <br />$("#myElement"). slideDown(“fast", function() {<br /> // This code is executed when the slide down is finished. <br />}<br /><ul><li>Similarly you have slideUp, slideToggle functions defined. </li></ul>To animate an element, you do so by telling jQuery the CSS styles that the item should change to. jQuery will set the new styles but instead of setting instantly, it does so gradually, animating the effect at chosen speed. <br />$("#myElement").animate(<br /> { opacity: .3, width: "500px", height: "700px"}, 2000, function() {<br /> // Optional callback calls after animation completes<br />});<br />
  126. 126. Events in jQuery<br />The below code inside function() will be executed when an anchor is clicked.<br />$("a").click(function() {<br /> // do something here when any anchor is clicked<br />});<br /> The following are some of the comment events you can use in jQuery:<br /><ul><li>blur,
  127. 127. focus,
  128. 128. hover,
  129. 129. keydown,
  130. 130. load,
  131. 131. mousemove,
  132. 132. resize,
  133. 133. scroll,
  134. 134. submit,
  135. 135. select.</li></li></ul><li>Chaining<br />One of the jQuery feature is chaining. If you call a method on a selection and that method returns a jQuery object, you can continue to call jQuery methods on the object without pausing for semicolon. (Powerful technique).<br />$('#content').find('h3').eq(2).html('new text for the third h3!');<br /><ul><li>Formatting the above chain code looks like below: (Good readability)</li></ul>$('#content')<br /> .find('h3')<br /> .eq(2)<br /> .html('new text for the third h3!');<br />If you change your selection in the midst of a chain, jQuery provides the $.fn.endmethod to get you back to your original selection.<br />$('#content').find('h3').eq(2)<br /> .html('new text for the third h3!')<br />.end() // restores the selection to all h3's in #content<br /> .eq(0)<br /> .html('new text for the first h3!');<br />
  136. 136. Type Checking<br />There are set of jQuery core methods define to check for non-primitive types.<br />$.isFunction();<br />$.isArray();<br />$.isPlainObject();<br />
  137. 137. jQuery Events<br />
  138. 138. Events Background<br />DOM is the standardized object model across different browsers. <br />DOM Level 2 Event Model<br /><ul><li>Multiple event handlers, or listeners can be established on an element.
  139. 139. These event handlers, can’t be relied upon to run on any particular order.
  140. 140. When triggered, the event propagates from the top down(capture phase) or bottom up (bubble phase).
  141. 141. IE doesn’t support “capture phase”. </li></ul>jQuery provides simple methods for attaching event handlers to selections. When an event occurs, the provided function is executed. <br /><ul><li>Inside the function, this refers to element that was clicked.
  142. 142. The event handling function can receive an event object. This object can be used to determine the nature of the event, and to prevent the event’s default behavior. </li></li></ul><li>Basic Syntax of Event Binding<br />Following is the syntax of event binding mechanism using $.fn.bind method: <br /><ul><li>Eg: $(‘img’).bind(‘click’, function(event) { alert(‘Howdy’; });</li></ul>$('p').bind('click', function() { alert('click'); } );<br /><ul><li>$(‘img’).bind(‘click’, imgclick(event));  $(‘img’).click(imgClick); </li></ul>Event binding with data using $.fn.bind method<br />$('input').bind( 'clickchange', // bind to multiple events<br /> { foo : 'bar' }, // pass in data<br /> function(eventObject) { console.log(eventObject.type, eventObject.data); });<br />To disconnect an event handler, you can use the $.fn.unbind() method and pass in the event type to unbind. <br /> $(‘p’).unbind(‘click’); //unbinding all click handlers. <br />$('p').bind('click', fooFunc).bind('click', barFunc); //Click binded with two funcs.<br />$('p').unbind('click', barFunc); //Unbinded only barFunc still fooFunc still binded.<br />If you attached a named function to the event, then you can isolate the unbinding to that named function by passing it as the second argument.<br /><ul><li>$(‘img’).unbind(‘click’, imgclick()); //Unbinding named function. </li></li></ul><li>Connecting Events to Run Only Once<br />If you need a particular handler to run only once -- after that, you may want no handler to run, or you may want a different handler to run. jQuery provides the $.fn.onemethod for this purpose.<br />$('p').one('click', function() {<br /> console.log('You just clicked this for the first time!');<br />$(this).click(function() { console.log('You have clicked this before!'); });<br />Some of the other event bindings examples are:<br /><ul><li>$(‘img’).one(imgclick);
  143. 143. $(‘img’).toggle(click1, click2);
  144. 144. $(‘img’).hover(mouseover, mouseout);</li></li></ul><li>Event Bindings<br />Some of the other event bindings examples are:<br /><ul><li>$(‘img’).one(imgclick);
  145. 145. $(‘img’).toggle(click1, click2);
  146. 146. $(‘img’).hover(mouseover, mouseout);</li></ul>Sometimes it can be useful to namespaces your events so you don’t unintentionally disconnect events that you don’t know about it. (Specially using in plug-ins).<br />$('p').bind('click.myNamespace', function() { /* ... */ });<br />$('p').unbind('click.myNamespace');<br />$('p').unbind('.myNamespace'); // unbind all events in the namespace<br />
  147. 147. Convince Method Event Binding<br />jQuery offers convenience methods for most common events, these methods are used very frequently. <br /><ul><li>These methods are: $.fn.click, $.fn.focus, $.fn.blur, $.fn.change,etc..,</li></ul> $('p').click(function() {<br /> console.log('click'); });<br /><ul><li>The above methods are shorthand for jQuery’s$fn.bindmethod.
  148. 148. This bind method is useful for binding the same handler function to multiple events, and is also used when you want to provide data to the event hander, or when you are working with custom events.</li></ul>The following are examples of event binding using convince method: <br /><ul><li>.click(func)
  149. 149. .submit(func)
  150. 150. .dblclick(func)
  151. 151. .mouseover(func)
  152. 152. .mouseout(func)
  153. 153. .select(func)</li></li></ul><li>Inside Event Handling Function<br />The event handling function receives an event object, which contains many properties and methods. <br /><ul><li>The event object is commonly used to prevent the default action of the event via the preventDefault method.
  154. 154. In addition to event object the event handler also has access to DOM element that that handler was bound via the key word ‘this’. To turn the DOM element into jQuery object by simply doing $(this).</li></ul>var $this = $(this);<br />Eg: $('a').click(function(e) {<br />var $this = $(this);<br /> if ($this.attr('href').match('evil')) {<br />e.preventDefault();<br />$this.addClass('evil'); } });<br />
  155. 155. Event Properties<br />The event object contains a number of useful properties and methods: <br /><ul><li>pageX, pageY //The mouse position at the time of event occur.
  156. 156. type //The type of event eg: “click”
  157. 157. which //The button or the key that was pressed.
  158. 158. data //Any data that was passed as second param of bind func.
  159. 159. target // The DOM element that initiated the event. Triggering elmt
  160. 160. target.id // Event triggering element ID.
  161. 161. currentTarget //
  162. 162. preventDefault() //Prevents the default action of event. Eg: following a link.
  163. 163. stopPropagation() //Stop the event from bubbling up to other elements. </li></ul>In addition to above properties you can find various mouse coordinate and key stroke related properties. <br />
  164. 164. Element Properties via “this”<br />You can retrieve the element properties with “this”<br /><ul><li>this
  165. 165. this.id
  166. 166. this.tagName
  167. 167. this.attr
  168. 168. this.src
  169. 169. this.classname
  170. 170. this.title
  171. 171. this.alt
  172. 172. this.value (for form elements)</li></li></ul><li>Event Methods<br />The following are the some of the event methods: <br /><ul><li>.stopPropagation() no bubbling
  173. 173. .preventDefault() no <a> link, no <form> submit
  174. 174. .trigger(eventType) does not actually trigger the event, but calls the appropriate function specified as the one tied to the eventType
  175. 175. .click(), blur(), focus(), select(), submit()
  176. 176. With no parameter, invokes the event handlers, like trigger does, for all the elements in the wrapped set</li></ul>The below are some of the useful Event functions: <br /><ul><li>.hide()display:none
  177. 177. .show()display:true
  178. 178. .toggle(func1, func2) first click calls func1, next click executes func2
  179. 179. .hover(over, out)mouseover, mouseout</li></li></ul><li>Triggering Events<br />jQuery provides a way to trigger the event handlers bound to an element without any user interaction via the $.fn.triggermethod. <br />While this method has its uses, it should not be used simply to call a function that was bound as a click handler. <br />Instead, you should store the function you want to call in a variable, and pass the variable name when you do your binding. Then, you can call the function itself whenever you want, without the need for $.fn.trigger.<br />varfoo = function(e) { <br /> if (e) { <br /> console.log(e); } <br /> else {<br /> console.log('this didn't come from an event!') }}; <br />$('p').click(foo); <br />foo(); // instead of $('p').trigger('click')<br />
  180. 180. Event Delegation<br />With event delegation, you can increase the performance of your code. <br />With event delegation, you bind your event to a container element, and then when the event occurs, you look to see which contained element it occurred on. <br />To support above delegation jQuery provides $.fn.live and $.fn.delegatemethods.<br />
  181. 181. Event Helpers<br />jQuery offers two event-related helper functions that save you a few keystrokes.<br /><ul><li>$.fn.hover//Mouse hover over an element.
  182. 182. $.fn.toggle</li></ul>The $.fn.hoverfunction lets you pass one or two functions to be run when the mouseenter and mouseleave events occur on an element. <br /><ul><li>If you pass one function it will be run for both events.
  183. 183. If you pass two functions, the fist will run for mouse enter, and the second will run for mouse leave. </li></ul>The $.fn.toggle method receives two or more functions; each time the event occurs, the next function in the list is called. <br />Generally, $.fn.toggle is used with just two functions, but technically you can use as many as you'd like.<br />$('p.expander').toggle(<br /> function() { $(this).prev().addClass('open');},<br /> function() { $(this).prev().removeClass('open'); } );<br />
  184. 184. jQuery Animations<br />
  185. 185. Effects<br />jQuery makes it trivial to add simple effects to your page. Effects can use the built-in settings, or provide a customized duration. <br />Frequently used effects are built into jQuery as methods. They are:<br />$.fn.show//Show the selected element. (Eg: $(‘h1’).show();)<br />$.fn.hide//Hide the selected elements.<br />$.fn.fadeIn//Animate the opacity of the selected element to 100%. <br />$.fn.fadeOut//Animate the opacity of the selected element to 0%. <br />$.fn.slideDown//Display the selected elements with a vertical sliding motion. <br />$.fn.slideUp//Hide the selected elements with a vertical sliding motion. <br />$.fn.slideToggle//Show or hide the selected elements with a vertical sliding. <br />Except $.fn.showand $.fn.hide, all of the built-in methods are animated over the course of 400ms by default. You can also change the duration of effect. <br />$('h1').fadeIn(300); // fade in over 300ms<br />$('h1').fadeOut('slow'); // using a built-in speed definition<br />jQuery has an object at jQuery.fx.speeds that contains the default speed, as well as settings for "slow" and "fast".<br />You can also create custom animations of arbitrary CSS properties<br />
  186. 186. Animation in jQuery<br />If you want to run some code after the animation has done, then you can register a callback function for that particular animation. <br />$('div.old').fadeOut(300, function() { $(this).remove(); }); <br />jQuery makes it possible to animate any arbitrary CSS properties via the $fn.animate method. This method lets you animate to a set value or to a value relative to the current value. <br />$('div.funtimes').animate( { left : "+=50", opacity : 0.25 }, //CSS properties<br /> 300, // duration<br /> function() { alert('done!'); // calback<br />});<br /><ul><li>Take note, color related properties can’t be animated with $fn.animate method. Color animations can be done by color plug-ins. </li></ul>jQuery provides several methods for managing animations: <br /><ul><li>$.fn.stop//Stop currently running animation on the selected element.
  187. 187. $.fn.delay//Waits for specified time before running next animation. </li></ul>$('h1').show(300).delay(1000).hide(300);<br />
  188. 188. Easing <br />Easing describes the manner in which an effect occurs -- whether the rate of change is steady, or varies over the duration of the animation. <br />jQuery includes only two methods of easing: swing and linear. <br />In addition various easing plug-in’s are available. <br />As of jQuery 1.4, it is possible to do per-property easing when using the $.fn.animate method.<br />$('div.funtimes').animate( { left : ["+=50", "swing" ], opacity : [ 0.25, "linear" ] }, 300);<br />
  189. 189. AJAX<br />
  190. 190. Ajax Overview<br />It is possible to trigger a AJAX request by Javascript code.<br /><ul><li>Javascript code sends a request to a URL, and when it receives a response, a callback function can be triggered to handle the response.
  191. 191. The XMLHttpRequest method (XHR) allows browsers to communicate with the server without requiring a page reload.
  192. 192. jQuery provides Ajax support that abstracts away painful browser differences.
  193. 193. jQuery offers both a full-featured $.ajax() method, and simple convenience methods such as $.get(), $.getScript(), $.getJSON(), $.post(), and $().load().
  194. 194. Most of jQuery applications use XML and they transport data as plain HTML and JSON.
  195. 195. In general, Ajax does not work across domains.
  196. 196. Exceptions are services that provide JSONP (JSON with Padding) support, which allow limited cross-domain functionality.</li></li></ul><li>AJAX Key Concepts<br />The two most common methods for sending request to a server are GET and POST. <br />The GET method should be used for non-destructive operations. <br /><ul><li>With GET request, you are only getting data from the server, not changing the data on the server. (Eg: Querying a search service).
  197. 197. GET requests may be cached by the browser.
  198. 198. GET request generally send all of their data in a query string. </li></ul>The POST method should be used for destructive operations (i.e., operation where you are changing data on the server). <br /><ul><li>POST requests are generally not cached by the browser.
  199. 199. A query string can be part of the URL, but the data tends to be separately as post data. </li></li></ul><li>Data Types<br />jQuery generally requires some instruction as to the type of data you expect to get back from an AJAX request. <br />Some times the data type is specified by the method name, in some other cases it is provided as part of a configuration object. <br />The different data types used in jQuery with AJAX requests are:<br /><ul><li>text // To tranport simple strings.
  200. 200. html // To transport blocks of HTML to be placed on the page.
  201. 201. script // Adding new script to the page.
  202. 202. json // To transport JSON-formatted data.
  203. 203. jsonp // To transport JSON data from another domain.
  204. 204. xml // to transport data in a custom XML schema. </li></li></ul><li>Same-Origin Policy and JSONP<br />In general, Ajax requests are limited to the same protocol (http or https), the same port, and the same domain as the page making the request. <br /><ul><li>This limitation does not apply to scripts that are loaded via jQuery's Ajax methods.
  205. 205. The other exception is requests targeted at a JSONP service on another domain. </li></li></ul><li>jQuery’s Ajax Related Methods<br />jQuery offers many Ajax related convenience methods, the heart of the all of the methods is $.ajax()<br />The $.ajax() method is powerful and straight forward way of creating Ajax requests. It offers ability to specify both success and failure callbacks. <br />Also the $.ajax() method has the ability to take a configuration object that can be defined separately makes it easier to write reusable code. <br />The configuration object contains all the instructions requires for jQuery to complete the request. <br />$.ajax({ url : ‘MyPage.php', data : { id : 123 }, //data converted into query string type: ‘GET’, //Request type either GET or POST<br />  dataType : ‘json’ // The type of data we expect back. <br />success: function(jsonRespObj) { …..}, //If request success, this code will run. <br /> error : function(xhr, staturs) {…}, //Code will run if request fails. <br />complete: function(xhr, status) { ..} //Code will run for both success and failure.<br /> });<br />
  206. 206. $.ajax method Options<br />There are many, many options for the $.ajax method, some of them are:<br /><ul><li>Async //Set false if you want to make synchronous request.
  207. 207. Cache //Whether to use cached response if available. Default is true for all //data types except script and jsonp.
  208. 208. Complete //Function to run after completion of request for (success or failure).
  209. 209. Context //The scope which callback functions would run.
  210. 210. Data //Data to be sent to server, it can be object or query string.
  211. 211. dataType //Type of data expect from server. Not specified look for MIME type.
  212. 212. Error //If request fails this callback function will be called.
  213. 213. Jsonp // Callback name to send in a query string making a jsonp request.
  214. 214. Success // If request success this function will be executed.
  215. 215. Timeout //Time to wait in milliseconds before saying request is failed.
  216. 216. Traditional //Specify to set serialization style.
  217. 217. Type //Specify the request type GET, POST, PUT and DELETE.
  218. 218. url //URL for the request. </li></li></ul><li>Convince Methods<br />Ajax convenience functions provided by jQuery can be useful, terse ways to accomplish Ajax requests. <br /><ul><li>These methods are just "wrappers" around the core $.ajax() method, and simply pre-set some of the options on the $.ajax() method.</li></ul>The convenience methods provided by jQuery are:<br /><ul><li>$.get() //Performs the GET request to the provided URL.
  219. 219. $.post() //Performs a POST request to the provided URL.
  220. 220. $.getJSON() //Performs a GET request and expects JSON response. </li></ul>Eg: $.get('/users.php', { userId: 1234 }, function(resp) {<br /> console.log(resp); });<br /><ul><li>All the above methods takes the following arguments in the given order:
  221. 221. url//Required. The URL for the request.
  222. 222. data //Optional. The data can be sent to server. It can be object //or query string (Eg: foo=bar&baz=bim)
  223. 223. scucesscallback//Optional. A callback routine need to run on succes
  224. 224. datatype//Optional. The data type that can expect from server. </li></li></ul><li>Convince Methods<br />The $.fn.load() method is unique among jQuery’s Ajax methods in that it is called on a selection.<br />$('#newContent').load('/foo.html');<br /><ul><li>The $.fn.load method fetches HTML from a URL, and uses the returned HTML to populate the selected element(s).
  225. 225. In addition to providing a URL to the method, you can optionally provide a selector; jQuery will fetch only the matching content from the returned HTML.</li></ul>The following example is a jQuery way to run a script from a script file. <br />$.getScript('/static/js/myScript.js', function() {<br />functionFromMyScript();<br /> });<br />
  226. 226. Ajax and Forms<br />jQuery’s AJAX capabilities can be especially useful when dealing with forms. jQuery Form Plug-in is a tool for adding Ajax capabilities to forms. <br />There are a two jQuery methods related to form processing are:<br /><ul><li>$.fn.serialize()
  227. 227. $.fn.serializeArray()</li></ul>Turning form data into query string:<br />$('#myForm').serialize();<br />Creating an array of objects containing form data <br />$('#myForm'). serializeArray();<br />
  228. 228. Working with jsonp<br />jQuery handles all the complex aspects of JSONP behind-the-scenes -- all we have to do is tell jQuery the name of the JSONP callback parameter specified by "callback“, and otherwise the whole process looks and feels like a normal Ajax request.<br />
  229. 229. AJAX Events<br />Ajax also supports set of events such as ajax request start or stop events. These events are useful for showing or hiding a loading indicator. <br />The following are the list of AJAX events:<br />Start<br />Stop<br />The following is a Setting up loading indicator. It can be used for all Ajax events:<br />$('#loading_indicator')<br /> .ajaxStart(function() { $(this).show(); })<br /> .ajaxStop(function() { $(this).hide(); });<br />
  230. 230. jQuery Plugins<br />
  231. 231. jQueryPlugins<br />The point of a jQuery plug-in is to extend jQuery's prototype object.<br />A jQuery plug-in is simply a new method that we use to extend jQuery's prototype object. <br /><ul><li>By extending the prototype object you enable all jQuery objects to inherit any methods that you add.
  232. 232. As established, whenever you call jQuery() you're creating a new jQuery object, with all of jQuery's methods inherited.</li></ul>The idea of a plug-in is to do something with a collection of elements. <br /><ul><li>You could consider each method that comes with the jQuery core a plugin, like fadeOut or addClass.</li></li></ul><li>References<br />jQuery Home page :<br />http://jquery.com<br />jQuery tutorial Blog:<br />http://learningjquery.com<br />http://visualjquery.com<br />Rick StrahI’s blog on jQuery : <br />http://www.west-wind.com/weblog/<br />Book : jQuery in Action : <br />
  233. 233. Thank You !<br />