• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content




JQuery Presentation

JQuery Presentation



Total Views
Views on SlideShare
Embed Views



5 Embeds 62

http://joefrancisninal.xtreemhost.com 49
http://joefrancisninal.info 8
http://www.linkedin.com 3
http://localhost 1
http://pfls.dev 1



Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

CC Attribution-NonCommercial LicenseCC Attribution-NonCommercial License

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

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

    jQuery jQuery Presentation Transcript

    • jQuery
      Writes less, Do More
      Ch. Vishwa Mohan
      Freelance Software Consultant &
      Corporate Trainer
    • Table of Contents
      jQuery Introduction
      jQuery Basics
      jQuery Core
    • jQuery Introduction
    • Evolution
    • 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
      • Browser differences
      Writing JavaScript code is tedious, time-consuming and error prone.
    • Why you might want to use jQuery
      jQuery makes writing Javascript much easier.
      • DOM Navigation (CSS-like syntax)
      • Apply methods to sets of DOM elements.
      • Builder model (chain method calls)
      • Extensible and there are tons of libraries
      • 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.
      • 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.
    • 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
    • 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.
      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
    • 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
      Open (free) licenseBooks
    • Who’s using jQuery?
    • jQuery Dominating
      Google trends comparison of JS Framework in last 12 months.
    • How to Embed jQuery in your Page
      By assigning your jQuery script file to the “src” property of script tag.
      <script src=“path/to/jquery-x.x.js"></script>
      // Start here
      <body> … </body>
      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
    • 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.,
      AJAX calls.
    • jQuery Basics
    • jQuery Philosophy
      The below is the illustration of how jQuery works:
      Find Some Elements
      Do something with them
      jQuery Object
    • 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:
      <p>I m a paragraph 1</p>
      <p>I m a paragraph 2</p>
      <p>I m another paragraph</p>
      • To select all paragraphs, you can use following jQuery : $(“p”)
      • 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
    • 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() {
      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(function(){ ….};)
    • jQuery Core
    • 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.
      • $(“#elmtID”); //Selecting elements by ID. ID must be unique.
      • $(“div.myClass”); //Selecting elements by class name.
      • $(‘input[name=myName]’); //Selecting elements by attribute.
      • $(‘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.
    • 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
      • $("#myElmtD"); // selects one HTML element with ID "myElement"
      • $(".myClass"); // selects HTML elements with class "myClass"
      • $("p#myElmtID"); // selects HTML paragraph element with ID "myElement"
      • $("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
      • $("input[type=text]"); // selects inputs that have specified type
      • $("a:first"); // selects the first anchor on the page
      • $("p:odd"); // selects all odd numbered paragraphs
      • $("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
      • $(":button"); // Selects any button elements (inputs or buttons)
      • $(":radio"); // Selects radio buttons
      • $(":checkbox"); // Selects checkboxes
      • $(":checked"); // Selects checkboxes or radio buttons that are selected
      • $(":header"); // Selects header elements (h1, h2, h3, etc.)
      • $(":disabled"); // Selects disabled form elements. (Enabled also there)
      • $(":img"); // Select inputs with type=“image”.
      • $(":file"); // Select inputs with type=“file”.
      • $(":password"); // Select inputs with type=“password”.
    • Selecting Elements Example
      The below are some of selectors examples:
      • $(selector) //The below are examples of selectors.
      • $(‘#id’) id of element.
      • $(‘p’) tag name.
      • $(‘.class’) CSS class
      • $(‘p.class’) <p> elements having the CSS class
      • $(‘p:first’) $(‘p:last’) $(‘p:odd’) $(‘p:even’)
      • $(‘p:eq(2)’) gets the 2nd <p> element (1 based)
      • $(‘p’)[1] gets the 2nd <p> element (0 based)
      • $(‘p:nth-child(3)) gets the 3rd <p> element of the parent. n=even, odd too.
      • $(‘p:nth-child(5n+1)’) gets the 1st element after every 5th one
      • $(‘p a’) <a> elements, descended from a <p>
      • $(‘p>a’) <a> elements, direct child of a <p>
      • $(‘p+a’) <a> elements, directly following a <p>
      • $(‘p, a’) <p> and <a> elements
      • $(‘li:has(ul)’) <li> elements that have at least one <ul> descendent
      • $(‘:not(p)’) all elements but <p> elements
      • $(‘p:hidden’) only <p> elements that are hidden
      • $(‘p:empty’) <p> elements that have no child elements
      • $(‘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://’.
      • $(‘a’[href$=pdf]) //Select <a> elmt with an href attribute ending with pdf
      • $(‘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.
    • 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();
      • $.each()
      • $.proxy() //Returns a function that will always run in the provided scope.
      • $.inArray() //Return a value’s index in an Array.
      • $.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).
    • 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');
      • $('div:visible').parent();
      • $('input[name=first_name]').closest('form');
      • $('#myList').children();
      • $('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() ); });
    • 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.
      • Here $ is another character there is no special meaning for it.
      • It is a convention and not mandatory.
      • Once you stored in variable you can call jQuery method on it.
      • 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.
      • Setters affects all elements in a selection.
      • 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
      • .size() number of elements in set
      • .end() reverts to the previous set
      • .get(n) get just the nth element (0 based)
      • .eq(n) get just the nth element (0 based) also .lt(n) & .gt(n)
      • .slice(n,m) gets only nth to (m-1)th elements
      • .not(‘p’) don’t include ‘p’ elements in set
      • .add(‘p’) add <p> elements to set
      • .remove() removes all the elements from the page DOM
      • .empty() removes the contents of all the elements
      • .filter(fn/sel) selects elements where the func returns true or sel
      • .find(selector) selects elements meeting the selector criteria
      • .parent() returns the parent of each element in set
      • .children() returns all the children of each element in set
      • .next() gets next element of each element in set
      • .prev() gets previous element of each element in set
      • .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
      • $("div").removeClass("content"); // removes class "content" from all <div> elmts
      • $("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.
    • 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
      • $("#myElemt").css("color", "blue") // makes text color blue on element #myElemt
      • $("ul").css("border", "solid 1px #ccc") // adds a border to all lists
      • $(“h1").css(‘fontSize’, ‘100px’); // Setting an individual property.
      • $(“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')) { ... }
    • 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>’);
    • 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.
      • 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.
      • $fn.attr(); //Get or set the value of the provided attribute.
      • $fn.val(); //Gets or sets the value of an form element.
      • $fn.width(); //Gets or sets the width in pixels of the first element in the // selection as an integer. Height is also there.
      • $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.
      • $fn.after(); //Places the element provided as an argument after the //selected element.
      • $fn.insertBefore();
      • $fn.before();
      • $fn.appendTo();
      • $fn.append();
      • $fn.prependTo();
      • $fn.prepend();
      The below is a simple jQuery code make the first list item the last list item.
      var $li = $('#myListli:first').appendTo('#myList');
    • 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.
    • 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,
      • 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.
      { opacity: .3, width: "500px", height: "700px"}, 2000, function() {
      // Optional callback calls after animation completes
    • 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:
      • blur,
      • focus,
      • hover,
      • keydown,
      • load,
      • mousemove,
      • resize,
      • scroll,
      • submit,
      • select.
    • 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)
      .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.
      .html('new text for the third h3!')
      .end() // restores the selection to all h3's in #content
      .html('new text for the first h3!');
    • Type Checking
      There are set of jQuery core methods define to check for non-primitive types.
    • jQuery Events
    • 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.
      • These event handlers, can’t be relied upon to run on any particular order.
      • When triggered, the event propagates from the top down(capture phase) or bottom up (bubble phase).
      • 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.
      • 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);
      • $(‘img’).toggle(click1, click2);
      • $(‘img’).hover(mouseover, mouseout);
    • Event Bindings
      Some of the other event bindings examples are:
      • $(‘img’).one(imgclick);
      • $(‘img’).toggle(click1, click2);
      • $(‘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('.myNamespace'); // unbind all events in the namespace
    • 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.
      • 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:
      • .click(func)
      • .submit(func)
      • .dblclick(func)
      • .mouseover(func)
      • .mouseout(func)
      • .select(func)
    • 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.
      • 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')) {
      $this.addClass('evil'); } });
    • Event Properties
      The event object contains a number of useful properties and methods:
      • pageX, pageY //The mouse position at the time of event occur.
      • type //The type of event eg: “click”
      • which //The button or the key that was pressed.
      • data //Any data that was passed as second param of bind func.
      • target // The DOM element that initiated the event. Triggering elmt
      • target.id // Event triggering element ID.
      • currentTarget //
      • preventDefault() //Prevents the default action of event. Eg: following a link.
      • 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.
    • Element Properties via “this”
      You can retrieve the element properties with “this”
      • this
      • this.id
      • this.tagName
      • this.attr
      • this.src
      • this.classname
      • this.title
      • this.alt
      • this.value (for form elements)
    • Event Methods
      The following are the some of the event methods:
      • .stopPropagation() no bubbling
      • .preventDefault() no <a> link, no <form> submit
      • .trigger(eventType) does not actually trigger the event, but calls the appropriate function specified as the one tied to the eventType
      • .click(), blur(), focus(), select(), submit()
      • 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
      • .show()display:true
      • .toggle(func1, func2) first click calls func1, next click executes func2
      • .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!') }}; 
      foo(); // instead of $('p').trigger('click')
    • 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.
    • Event Helpers
      jQuery offers two event-related helper functions that save you a few keystrokes.
      • $.fn.hover//Mouse hover over an element.
      • $.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.
      • 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.
      function() { $(this).prev().addClass('open');},
      function() { $(this).prev().removeClass('open'); } );
    • jQuery Animations
    • 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
    • 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.
      • $.fn.delay//Waits for specified time before running next animation.
    • 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);
    • AJAX
    • 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.
      • The XMLHttpRequest method (XHR) allows browsers to communicate with the server without requiring a page reload.
      • jQuery provides Ajax support that abstracts away painful browser differences.
      • jQuery offers both a full-featured $.ajax() method, and simple convenience methods such as $.get(), $.getScript(), $.getJSON(), $.post(), and $().load().
      • Most of jQuery applications use XML and they transport data as plain HTML and JSON.
      • In general, Ajax does not work across domains.
      • 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).
      • GET requests may be cached by the browser.
      • 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.
      • 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.
      • html // To transport blocks of HTML to be placed on the page.
      • script // Adding new script to the page.
      • json // To transport JSON-formatted data.
      • jsonp // To transport JSON data from another domain.
      • 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.
      • 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.
    • $.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.
      • Cache //Whether to use cached response if available. Default is true for all //data types except script and jsonp.
      • Complete //Function to run after completion of request for (success or failure).
      • Context //The scope which callback functions would run.
      • Data //Data to be sent to server, it can be object or query string.
      • dataType //Type of data expect from server. Not specified look for MIME type.
      • Error //If request fails this callback function will be called.
      • Jsonp // Callback name to send in a query string making a jsonp request.
      • Success // If request success this function will be executed.
      • Timeout //Time to wait in milliseconds before saying request is failed.
      • Traditional //Specify to set serialization style.
      • Type //Specify the request type GET, POST, PUT and DELETE.
      • 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.
      • $.post() //Performs a POST request to the provided URL.
      • $.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:
      • url//Required. The URL for the request.
      • data //Optional. The data can be sent to server. It can be object //or query string (Eg: foo=bar&baz=bim)
      • scucesscallback//Optional. A callback routine need to run on succes
      • 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.
      • The $.fn.load method fetches HTML from a URL, and uses the returned HTML to populate the selected element(s).
      • 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() {
    • 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()
      • $.fn.serializeArray()
      Turning form data into query string:
      Creating an array of objects containing form data
      $('#myForm'). serializeArray();
    • 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.
    • 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:
      The following is a Setting up loading indicator. It can be used for all Ajax events:
      .ajaxStart(function() { $(this).show(); })
      .ajaxStop(function() { $(this).hide(); });
    • jQuery Plugins
    • 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.
      • 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 :
      jQuery tutorial Blog:
      Rick StrahI’s blog on jQuery :
      Book : jQuery in Action :
    • Thank You !