Friday, February 1, 2013

jQuery

Purpose

  • Select elements of HTML DOM
  • Style selected elements
  • Copy, delete, move, modify, animate DOM elements
  • Hook up event handlers to DOM elements
  • AJAX

Usage Pattern

  1. Allow the DOM for web page to be load
  2. jQuery allows us to hook-in an initialization function when DOM is fully loaded (ready())
  3. Select or traverse for DOM elements of interest
  4. Manipulate DOM elements - apply CSS styles, copy, delete, move, modify, animate, hook up event handlers

How to Include

<head>
..
  /* Full and minified versions are available */
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
..
</head>

Initialization - Ready Handler

<script type="text/javascript">
$(document).ready(function() {
   // apply CSS styles, copy, delete, move, modify, 
   // animate, hook in event handlers
}
</script>

Shorthand:
$(function(){});

Example:
// show an alert when a link is clicked
$(
    function()   // ready handler function
    {      

        // attach a function to click of a link
       $("a").click(

               function()   // click handler function
             {  
                  alert("Hello world!");
             }   // end -click handler function

           );

     }   // end - ready handler function
);

Selectors

$( ) is an alias for jQuery()

By Element Name
$('div')

By Id
$('#elementid')

By Class
$('.className')

By Element attributes
$('[padding]')  // elements with padding attrib
$('div[padding]')  // divs with padding attrib
$('div[padding=10]')  // divs with padding of 10
$('div[padding!=5]')  // divs with not padding of 5

By Element Visibility
$(':visible')  // visible elements
$(':hidden')  // hidden elements

By Element Order
$('p:first')  // first paragraph
// other options
// :first :last :even :odd :eq(index)
// :gt(index) :lt(index)

Form Fields
$(':input')  // all input form fields
// other options
// :input :text :radio :checkbox :checked

Parents or Children Elements
$('div:first-child')  // first child of the body
// other options
// :last-child 
// parent > child
$('div > p');  // all p elements within the divs
$("#elementid > div") // all <div> elements that are 
       // children of the element 
       // with an id of "elementid"

By lineage
$('#elementid div') // all <div> elements that are 
  // descendants of the element with 
  // an id of "elementid"

Combination
$('div[width=600] > p');   // all p elements inside 
               //div having width=600
$('div[width=600] > p.intro');   // all p elements of class intro
               // inside div having width=600
$('div[width=600] > p#elem_id');   // all p elements with elem_id
               //inside div having width=600
$('div, p, span); // all divs, p, span

By psuedo-classes
$("a:even") // all evenly numbered anchor tags
$("a:odd") // all odd numbered anchor tags

DOM Traversal

  • each()
  • first()
  • last()
  • next()
  • prev()
  • parent()
  • children()
  • siblings()
$("#elementId").each(
  function(index, element){
  }
});

or

$("#elementId").each(
  function(){
    // $(this).  provides access the element
  }
});

Changing CSS Styles

  • css('attributeName')
  • css('attributeName', 'value')  // changes attribute
  • css({'attributeName', 'value'})  // use single quote for attribute name if it has an embedded -
      // Or use camel case for the attribute name borderWidth instead of border-width
  • addClass()
  • toggleClass()  // separate multiple class names with a space
  • hasClass()
var currentWidth = $("#elementId").css('width');

DOM Manipulation

  • val()   // get/set values of form fields
  • html()  // text including the html tags
  • text()  // text inside an element
  • attr()  // read/write attributes
  • removeattr()  // remove an attribute
  • clone()      // make an exact copy of a selected element
                    //   the event handlers can be optionally cloned
  • append()   // insert new html at the end
  • prepend()  // insert new html at the beginning
  • before()  // insert new html before the outside of element
  • after()    //  insert new html after the outside of element
  • insertBefore()  // move element from one place to another
  • insertAfter()    // move element from one place to another
  • wrap()  // wrap the selected element into another element
  • replaceWith()  // replace element with another one
  • replaceAll()    // replace all instances with another one
  • remove()        // remove the selected element
  • empty()          // remove all child elements of the selected element

  • data()   // attach or access data from an element
                // data is key-value; value can JSON object, string, number
  • removeData()   // remove data from an element

Handling Events

  • $(document).ready()
  • click()
  • dblclick()
  • mouseenter()/mouseleave()
  • mouseover()/mouseout() // mouse enter/leave on the parent when pointer is over child
  • mousedown()
  • mouseup()
  • mousemove()
  • hover()
  • toggle() - takes one or more functions, executes one based on number of times clicked
  • focus()
  • blur() // form field loses focus
  • keydown() // Key events can be on divs and spans // must have tabindex and focus receive these events
  • keyup()
  • keypress()
// in ready handler
$('#btnId').click(function() {
alert('hello!');
});

Visual Effects

  • show() // show a hidden element
  • hide()
  • toggle() // toggle visibility
  • slideDown() // slide down a hidden element (now visible)
  • slideUp() // slide up a visible element (now hidden)
  • slideToggle()
  • fadeIn()
  • fadeOut()
  • fadeToggle()
  • fadeTo() // partially fade an element (transparency)
  • animate() // animate attributes (borderWidth, fontsize, etc) of element

AJAX calls

// Simple GET query request - data received is un-parsed (raw, e.g. HTML fragment)
var jqxhr =
$.ajax(
{
url: "/url/of/resource",
// parameters sent to the server as  
// query string or post body
data:
{
searchstring: "find this",
searchoption: "all_fields"
}
})
.success(
function(response)
{
// alert("Success! Response: " + response);
// insert the response into the document
$('#elemId').html(response);
}
)
.error(
function(jqXHR, textStatus, errorThrown)
{
alert("Error: " + textStatus + ' - ' + errorThrown);
}
)
.complete(
// always called upon completion
function()
{
}
)

// Receiving JSON from Server {"result_count": "5"}
var jqxhr =
$.ajax(
{
url: "/url/of/resource",
  dataType: 'json',
// parameters sent to the server as  
// query string or post body
data:
{
searchstring: "find this",
searchoption: "all_fields"
}
})
.success(
function(response)
{
$('#elemId').html('<div>Result count: ' + response.result_count + '</div>');
}
)
.error(
function(jqXHR, textStatus, errorThrown)
{
alert("Error: " + textStatus + ' - ' + errorThrown);
}
)
.complete(
// always called upon completion
function()
{
}
)

// POSTing a form
// Server returns JSON
// {
//  "head" : { code: 'OK'},
//   "body" : { }
// }

// Form has Search string and Search option and uses POST action
// Hookup the submit button
<script type="text/javascript">
$(document).ready(
function()
{
$('submitButton').click(
function()
{
submitForm();
}
}
)
</script>

// AJAX to submit the form
<script type="text/javascript">
function submitForm()
{
var submitData = {};
submitData.searchstring = $('#searchstr').val();
submitData.searchoption = $('#searchoptions').val();

$.ajax(
{
url: "/url/of/resource",
type: 'POST',
dataType : 'json',
data: submitData
})
.success(
function(response)
{
alert("Success! Response Code: " +
response.head.code);
}
)
.error(
function(jqXHR, textStatus, errorThrown)
{
alert("Error: " + textStatus + ' - ' + errorThrown);
}  
.complete(
// always called upon completion
function()
{
}
)
}
</script>

// Sending Raw Data to the Server
var jqxhr =
$.ajax(
{
url: "/url/of/resource",
// parameters sent to the server as raw data
processData: false,
data: "SOME DATA STRING"
})
.success(
function(response)
{
$('#elemId').html(response);
}
)
.error(
function(jqXHR, textStatus, errorThrown)
{
alert("Error: " + textStatus + ' - ' + errorThrown);
} .complete(
// always called upon completion
function()
{
}
)

Passing in jQuery as $

$(function ($) {..})(jQuery); wraps the code so that $ is jQuery inside that closure, even if $ means something else outside of it, usually as the result of $.noConflict() call

jQuery Plugin

// jQuery plugin being created within the ready handler
$(
function ($) 
{
// jquery plug-in $.fn.plugInFunctionName = function () 
{
}
}
)
(jQuery);

Now the plugin can be called as follows:
$(selector). plugInFunctionName ();

Reference