Saturday, October 17, 2015

JQuery - Handout - quick memory refresher

Introduction:
This post is to provide some quick refreshing facts and best practices for those folks who haven't worked on jQuery for a while. For beginners, it's better to go through the basic/advance tutorials first and check back with this later.

About jQuery:

1. jQuery is a JavaScript Library
2. jQuery greatly simplifies JavaScript programming


jQuery concepts:

  1. Pointing to jQuery
    • From local reference - ''- assuming jquery.js file is in same folder with the html
    • Content Delivery Network (CDN) based - 'src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"'
       
  2. launching code - Option-02 is prepared as that's invoked as soon as the DOM is ready rather waiting the page loaded fully (including images)
    1. Option-01: window.onload = function() { //code};
    2. Option-02: $( document ).ready(function() { //code });
    3. Option-03: is shortcut to option-02. '$(function(){ //code});'
       
  3. Callbacks and functions - A callback is a function that is passed as argument to another function and will be executed only after the function where it's passed has completed
    1. Callback without Arguments - '$.get('aPage.html', callBackFn);'
    2. Callback with Arguments - 
      1. Not possible - '$.get('aPage.html', callBackFn(param1, param2));'. This will execute the callBackFn first and return of it will be passed to get function
      2. Correct way - '$.get( "aPage.html", function() { callBackFn( param1, param2 ); });'
         
  4. $ vs $()
    1. Methods called on jQuery selections (used $()) are in the $.fn namespace, and automatically receive and return the selection as this
    2. Methods in the $ namespace are generally utility-type methods, and do not work with selections; they are not automatically passed any arguments
        
  5. Ways to avoid conflict with other libraries
    1. new alias - noConflict returns a reference to jQuery function
      'var $j = jQuery.noConflict();'
    2. use self invoking function -
      'jQuery.noConflict();(function($){ //code})(jQuery);'
    3. Argument through jQuery(document).ready() function
      'jQuery(document).ready(function( $ ) { // code });'
       
  6. Selecting elements
    1. by 
      1. tag name - '$("aDOM");'
      2. ID - '$("#idToFind");'
      3. class name - '$(".className");'
    2. Pseudo selectors - :visible :enabled :checked :text :button :file (see references for complete list)
    3. comma to use to select multiple DOM objects
    4. chaining - any method call on a selection returning a jQuery object, allows to call jQuery method on the object without pausing for a semicolon.
      '("#aDiv").find("p").eq("1").html("Changed text");' - find second p in a dive called aDiv and change content
       
  7. Methods - 
    1. getter/setter - html, text, val - can be both setter (with argument) or getter (no argument) 
    2. Move, copy and remove elements
    3. Attributes - .attr() to get/set value to selector's attribute.
      1. Object of key-value pair can be passed to set multiple
         
  8. Selection traversing
    1. parents - .parent() .parents() .parentUntil() .closest()
    2. children - .children() .find().
    3. Siblings - .prev() .next() .siblings() .nextAll() .prevAll() .nextUnti() .prevUntil()
    4. Styling and dimensions
    5. CSS classes - addClass("aClass") removeClass("aClass").
    6. Dimensions - width, height - getter/setter
        
  9. Data methods - stores data to the element and manages the memory issues.
    '$("#aDiv").data("aKey", {name:"Riaz"});' '$("#aDiv").data("aKey");'
      
  10. Utility methods - 
    1. $.trim() - 
    2. $.each() - generic iterator function for looping over object/arrays/ array-like objects
      example:
      '$.each([1,2,3,4], function(idx, val){ console.log("Element "+idx + " is "+val);});'
      output:
      Element 0 is 1
      Element 1 is 2
      Element 2 is 3
      Element 3 is 4
       
    3. $.proxy(function, scopeObj) -
      example:
      var aFn = function() { console.log( this ); };
      var aObj = { name: "Riaz" };
      aFn();
      var proxyAFn = $.proxy( aFn, aObj );
      myProxyFunction();

      Output:
      Window {external: Object, chrome: Object, document: document, speechSynthesis: SpeechSynthesis, caches: CacheStorage…}
      Object {name: "Riaz"}
       
    4. $.type() - returns the type of passed object
    5. .map() - returns array from matched elements from selector
        
  11. jQuery events - 
    1. Some common events
    2. Mouse Event Key Event Form Event window Event
      click keypress submit load
      dblclick keydown change unload
      mouseenter keyup focus size
      mouseleave    blur scroll
    • Event call syntax - 
      • Assign an event - $("p").click();
      • Indicates what should happen after event -
        $("p").click(function(){ /*actions*/});
    • Usage of '.on()'. 
      • All the methods above are shortcut of this
      • Syntax - '$("p").on("click", function(){/*actions*/});'
    • Handling event - 
      • Many events single event handler - comma separated events
      • Multiple event and event handler association -'$( "p" ).on({ "click": function() { console.log( "clicked!" ); },
        "mouseover": function() { console.log( "hovered!" ); } });
        '
      • Data can be passed to event -
        '.on( "click", {name:"Riaz"}, function(event){ console.log("Name:"+event.data.name");});'
    • Instead of anonymous function, a named function can be passed as event handler 
    • Namespacing event - for complex and plugin application, it's a good idea to namespace application specific events to avoid conflict 
    • tead down events
      • Unbind all click event - $( "p" ).off( "click" ); 
      • Unbind only aHandler from click - $( "p" ).off( "click", aHandler );
    • Event handler to run only once - using '.one(...)'
    • Properties and method of eventhanlder
      • Properties - pageX pageY which type data target namespace timestamp etc.
      • Methods - preventDefault() stopPropagation() etc
12. Ajax in jQuery
  • Syntax - '$.ajax(...)'
  • Data types - type of data you expect to get back from an Ajax request
    • text html script json jsonp xml
  • API -
    // Using the core $.ajax() method
    $.ajax({
    // The URL for the request
    url: "- page url",
    // The data to send (will be converted to a query string)
    data: {  },
    // Whether this is a POST or GET request
    type: "GET",
    // The type of data we expect back
    dataType : "json",
    // Code to run if the request succeeds;
    success: function( json ) { /* do something */ },
    // Code to run if fails; raw request and status codes are passed
    error: function( xhr, status, errorThrown ) { /* do something */ },
    // Code to run regardless of success or failure
    complete: function( xhr, status ) { /* do something */ } });
  • Convenient functions - below functions are wrapper around core .ajax()
    • functions - $.get $.post $.getScript $.getJSON
    • parameters - 
      • Required - url
      • Optional - data success dataType
  • Ajax events
    • Local events - specify within ajax request object
      • beforeSend success error complete
    • Global events
      • ajaxtStart ajaxStop
13. Serializing form data
  • Using $("#aForm").serialize() - serializes form data into a query string
  • Using  $("#aForm").serializeArray() - serializes to array of objects

Resources:
1. http://api.jquery.com/
2. http://www.w3schools.com/jquery/
3. https://learn.jquery.com/

    No comments: