jQuery

  • 2,655 views
Uploaded on

JQuery Presentation

JQuery Presentation

More in: Education , Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
2,655
On Slideshare
0
From Embeds
0
Number of Embeds
5

Actions

Shares
Downloads
0
Comments
0
Likes
5

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

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