jQuery jQuery JavaScript Library

This document contains code samples that are color coded. Use these buttons to change the colors for easier reading.

jQuery is the most frequently used JavaScript (JS) library. jQuery has a compact syntax which is often faster to code than JS. jQuery also provides cross-browser support which eliminates the need to write special JS code for particular browsers. It has short selector statements that find HMTL elements quickly. It handles events, Ajax calls, and the animation of HTML elements. There are many plugins available for jQuery to add extra functionality. More details about its usage and history can be found on this page.

The jQuery library can be downloaded from jquery.com. The production version of the code is minified (whites pace removed). The development version of the code is in a human-readable format. Documentation navigation for the main features of jQuery is available was well as the complete API documentation. A good site for Learning jQuery is maintained by Karl Swedberg. An interactive jQuery lab for practicing jQuery is maintained by Cody Lindley.

The jQuery .js file can be stored locally or can be obtained from a Content Deliver Network (Microsoft or Google). Using a CDN can have the benefits of caching, obtaining a copy of jquery.js which is closer to the user, and improved chance of parallism since it resides on a different domain. A local copy can be used as a "fall back" to a CDN version, as shown below, in case the CDN version would happen to be unavailable.

<head>
  <!-- Get jQuery from Google's Content Deliver Network -->
  <!-- <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> -->
  
  <!-- Get jQuery from Local Storage when Doing Development -->
  <script src="js/jquery-1.8.3.min.js"></script>

  <!-- Fall Back jQuery from Local Storage -->
  <script>window.jQuery||document.write('<script src="jquery.js"></script>')</script>
</head>

Two versions of jQuery are currently available: 1.x and 2.x. Use 1.x for supporting versions of IE prior to version 9. For IE 9 and later versions, use 2.x. We use the following conditional to switch between the two files to provide support for IE 8 and above. At this writing (May 2015) IE 8 still has a 16% market with IE 11 having a 25% market share, NetMarketShare.

<!--[if lt IE 9]>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<![endif]-->
<<!--[if (gte IE 9) | (!IE)]><!-->
  <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!--<![endif]-->

jQuery Syntax
jQuery uses the $(document).ready() syntax to determine when the page DOM has fully loaded. However this ready() function may trigger before all the images have loaded. This differs from the JS onload event which waits for the entire page to load (including all the images). So during a page load the jQuery may trigger sooner that a JS onload.

<!-- JS Onload Event -->
<body onload="myFunction()">


<!-- jQuery Ready Function -->
<script>
   $(document).ready(function() {
      // Function statements
   });
</script>

$ is an alias the jQuery keyword, so "jQuery(document)" is the same as "$(document)". Most developers use the $ syntax. $() puts a jQuery wrapper around an object, so $(document) puts a wrapper around the document object. The ".ready" function call can either be an anonymous inline function or a named call-back function. Most frequently an anonymous in-line function is used.

Note: the jQuery $(document).ready() function fires after the DOM structure is built (but before all the images are loaded), while the JavaScript OnLoad= function fires later after the DOM structure is build and the images have been loaded.


jQuery Selectors

Selectors are a way to select a node (tag, element) from the DOM. Below is the test page used to compare the JS selectors with the jQuery equivalent. In each test the jQuery Ready function fired before the JS Onload event. JS is in blue, jQuery is in red, and HTML is in green.

<!DOCTYPE html> 
  <head>
  <title>Testing Page</title> 
  <script src="js/jquery-1.8.3.min.js"></script>
  <script> 
  
  // JavaScript
  function myFunction() {
    var x = document.getElementsByTagName("h1");
    for (i=0;i<x.length;i++) 
       alert("JS: " + x[i].innerHTML);
  }
  
  
  // jQuery
  $(document).ready(function() {
    var x = $("h1"); 
    for (i=0; i<x.length; i++) 
       alert("jQ: " + x[i].innerHTML);
  });
  
  </script>
  </head> 
  <body onload="myFunction()">
  
    <h1>First header.</h1>
    <h1>Second header.</h1>
      
   </body>
</html>


Select by Tag Name
The tag name is the also referred to as the type of the HTML tag (e.g. a=anchor, p=paragraph). Example of selecting by tag name include:

$('p') selects all the paragraph tags

$('a') selects all anchor tags

$('a, p , span') selects all the anchor, paragraph, and span tags

$('table tr') selects all the tr tags that are descendants of the table tag

The JavaScript vs jQuery code below returns a list of h1 tags which is then accessed to retrieve the text inside each node.

  
  // JavaScript
  function myFunction() {
    var x = document.getElementsByTagName("h1");
    for (i=0;i<x.length;i++) 
       alert("JS: " + x[i].innerHTML);
  }
  
  
  // jQuery
  $(document).ready(function() {
    $("h1").each(function() {
       alert("jQ: " + $(this).text());
    });
  });
  
  
    <h1>First header.</h1>
    <h1>Second header.</h1>
      

Note: There is an .innerText property that is supported in some browsers, while other browsers only support the .textContent for returning the text inside a node. The jQuery .text() will work in all browsers. An alternative is to use regular expressions with .innerHTML to remove the HTML.


Select by ID
Selecting by ID is the fastest way to select a node. Only one node is returned, so in JS it is the singular word Element. In jQuery use the # inside the selector to indicate it is an ID. An example of selecting by tag ID is:

$('#theID') selects the tag with ID="theID"

Both of these code sections return the string: <p>First division.</p>.

  
// JavaScript
function myFunction() { var x = document.getElementById("one"); alert("JS: " + x.innerHTML); }
// jQuery $(document).ready(function() { alert("jQ: " + $("#one").html()); }); <div id="one"><p>First division.</p></div> <div id ="two"><p>Second division.</p></div>



Select by Class Name
In jQuery use a period inside the selector to indicate it is a class name. Selecting by class name is not as fast as selecting by ID, as it requires scanning of the entire DOM to find all the classes with a matching name. Examples of selecting by class name include:

$('.theClass') selects all the tags with CLASS="theClass"

$('.theClass').css('border', 2px solid red); adds a red border to all matching classes

$('.GreenDiv, BlackDiv') selects all the tags with either class

The code below returns a list of div tags that have a class name of "one", which is then accessed to retrieve the HTML inside each node. Both of these code sections return the strings: <p>First division.</p> and<p>Third division.</p>. Note: .getElementsByClassName has only been recently supported in some browsers. Check the quirksmode.org. web site to check for browser compatibility.

  // JavaScript
  function myFunction() {
    var x = document.getElementsByClassName("one");
    for (i=0;i<x.length;i++) 
       alert("JS: " + x[i].innerHTML);       
  }  
  
  // jQuery
$(document).ready(function() {
$(".one").each(function() {
alert("jQ: " + $(this).html());
});
});
<div class="one"><p>First division.</p></div>
<div class="two"><p>Second division.</p></div>
<div class="two one"><p>Third division.</p></div>

Note: When selecting by class name it is more efficient to add the tag name to the selector. For example a more effect selection for the above jQuery would be $("div.one"). Also jQuery allows for multiple class specifications, such as: $(".one, .two").

Note: It is more efficient to combine the tag type along with the tag Class. For example, the following is more efficient than selecting by class alone:

$('a.theClass') selects only anchor tags with CLASS="theClass"


Select by Attribute Value
There is no getElementsByAttribute method in JavaScript. To get nodes by their attributes in jQuery you specify the attribute in brackets []. Think of brackets as a Where clause. You can future specify the attribute values in the selector. The jQuery code section returns the strings: <p>First division.</p> and<p>Third division.</p>.

 JavaScript
 // No getElementsByAttribute exists.

// jQuery
$(document).ready(function() {
$("div[title='Div One']").each(function() {
alert("jQ: " + $(this).html());
});
});
<div title="Div One"><p>First division.</p></div>
<div title="Second"><p>Second division.</p></div>
<div title="Div One"><p>Third division.</p></div>
Note: The attribute select string is case-sensitive and can be omitted. If omitted it only matches on the attribute, not the attributes value. For example $("div[title]") would return all three divisions.

Another example will change all the background of all the input text boxes to red:

  var myInputs = $("input[type='text']");
  myInputs.css("background-color","red");


Attribute Selection Operators
Additional operators for selection attributes by value are listed in the table below.


   $'input[value^="searchValue"]')

Attribute Selection Operators
Operator Selection
= exact match (case-sensitive)
!= not equal to the searchValue
^= starts with searchValue
$= ends with searchValue
~= contains searchValue as a word
*= contains searchValue anywhere


Hierarchy Selectors child, siblings, parent
Name Selector Returns
Immediate Child Selector $("parent > child") All direct child elements of a given parent.
Descendant Selector $("ancestor descendant") All elements that are descendants of a given ancestor.
General Sibling $("child ~ child") All elements which are siblings
Adjacent Sibling $("child + child") All sibling elements which are immediately next to the child.


Extension Selectors Further Restrictions
There are extensions that can be added to the jQuery selectors which will further restrict the results. For example the selector $("p:first") will return the first paragraph on a page.

Useful Extension Selectors
Selector Returns
:contains(text) Elements that contain the specified text.
:eq(n) Element at the nth index (0-based).
:even Even-numbered elements (1-based).
:first First matched element.
:first-child Elements that are first child of parent.
:gt(n) Elements with an index greater than n (0-based).
:has(selector) Elements that contain at least one element that matches the specified selector.
:last Last matched element.
:lt(n) Elements with an index smaller than n (0-based).
:odd Odd-numbered elements (one-based).
:text Text elements.


Type Extension Selectors Further Restriction by Type
There are extensions for types of HTML elements that can be added to the jQuery selectors. For example the selector $(":input") will return all the input controls on a page.

Further Restriction by Types
Selector Returns
:button All input elements with type=button.
:checkbox All input elements with type=checkbox.
:header All header elements (h1...h6).
:hidden All hidden elements.
:input All input elements.
:password All input elements with type= password.


Extending Selector Engine Creating Your Own Selectors
It is possible to extend the capabilities of the jQuery selector engine. Below is an example of how to create an extension that will return all paragraphs that have the color attribute of blue:

// jQuery Define extension to check for color blue
$.extend($.expr[':'],{
   blue: function(a) {
      return $(a).css('color') === 'blue';
   }  
});

  // jQuery Select paragraphs with blue color
 $('p:blue');
 

Adding Methods to Selectors Determining Type of Input Control
Methods can be chained to selectors to perform actions on the resulting collection of nodes. For example the .each() method will loop thru the collection of nodes. The example below loops through all the input controls using the .each() method attached to the $(":input") selector, and returns the value of the controls with the .val() method.


<!-- Drop Down List is created with select statement -->
<label for="selBkImage">Drop down list is created with select statement.</label> 
<select id="selBkImage" style="margin: 5px 0 0 0" onChange="changeBackground(this);">
   <option value="0">Optical Gray</option>
<option value="1">Pattern Gray</option>
<option value="2">Cloth Gray</option>
<option value="3">Marble Gray</option>
</select>




<!-- Text Area is created with textarea statement -->
<label for="comments">Text area is created with textarea statement.</label> 
<textarea id="comments" rows="3" cols="40">Default text area text.
</textarea>




Search Option

<!-- Radio Buttons created with input/radio statement -->
<fieldset>
<legend align="center"><b>Search Option</b></legend> <input id="yes_search" type="radio" name="searchoption" onchange="disablesearch()" style="padding: 5px 0 15px 0" checked></input> <label for="yes_search">Display Search Options</label> <input id="no_search" type="radio" name="searchoption" onchange="disablesearch()" style="padding: 5px 0 5px 0"></input> <label for="no_search">No Search - Show all Photos</label> </fieldset>



Save Settings

<!-- Checkboxes created with the input/checkbox statement -->
<fieldset>
<legend align="center"><b>Save Settings</b></legend> <input type="checkbox" name=ssave id="ssession" value="ssession" checked /> <label for="ssession">This Session Only</label> <input type="checkbox" name=ssave id="fsession" value="fsession" checked /> <label for="fsession">Future Sessions</label> </fieldset>



First name:

<!-- Text Box created with the input/text statement  -->
First name: <input type="text" name="firstname">  





<!-- Button created with the input/button statement  -->
<input type="button" value="Hello" onClick="alert('Hello World!')";>





<!-- Hidden Field and Submit Button -->
<form method='get' action='photodb.php' onsubmit='test();'> <input type='hidden' id='sql' name='sql' /> <input type='submit' class='searchButton' value='Display Photos' style='padding: 10px' /> </form>


jQuery Loops Thru Input Controls Defined Above
// jQuery code for testing val() method.
  $(document).ready(function() {
$(":input").each(function() {
var theTagName = $(this)[0].tagName;
if (theTagName == "INPUT") {
var theType = $(this)[0].type;
} else {
var theType = "NoType";
}
var theVal = $(this).val();
alert("TagName: " + theTagName + " Type: " + theType + " Val: " + theVal);
});
});
Results for jQuery val() Method
Control Tag Name Type val()
1. select NoType 0
2 textarea NoType Default text area text.
3. input radio on,on
4. input checkbox ssession, fsession
5. input text  
6. input button Hello
7. input hidden  
8. input submit Display Photos



Methods jQuery Methods by Category

Core Methods
Method Description
.holdReady() Hold and releases execution of jQuery ready event.
.noConflict() Remove jQuery's association with $.
.when() Execute callback functions.

CSS Methods
Method Description
.addClass() Adds class to matched selector elements.
.css() Get or set the style property of the matched selector elements.
.hasClass() Determine if matched elements have a particular class.
.removeClass() Removes class from matched selector elements.
.toggleClass() Alternate adding and removing one or move classes to matched selector elements.

Event Methods
Method Description
.bind() Attach an event handler to elements.
.blur() Attach a "blur" event handler to elements.
.change() Attach a "change" event handler to elements.
.click() Attach a "click" event handler to elements.
.hover() Attaches multiple event handlers when mouse enters or leaves element.
.keypress() Attach a "keypress" event handler to elements.
.mouseleave() Attach event handler to be fired when the mouse leaves the elements.
.on() Attach event handler for one or more events to the selected elements.
.toggle() Attach event handlers to matched elements, to be executed on alternate clicks.

Form Methods
Method Description
.serialize() Encode a set of form elements as a string from submission
.serializeArray() Encode a set of form elements as an array of names and values.
.submit() Attach a "submit" event handler to elements.
.val() Get or set the value of the selected elements.

Manipulation Methods
Method Description
.append() Insert content to the end of selected elements.
.attr() Get or set the value of an attribute for selected elements.
.css() Get or set the value of a style property for selected elements.
.html() Get or set the HTML contents for selected elements.
.prepend() Insert content at the beginning of selected elements.
.text() Get or set the text contents for selected elements.

Traversing Methods
Method Description
.each() Iterate over selected elements, executing a function on each iteration.
.eq() Reduce the set of matched elements to the one at the specified index.
.filter() Reduce the set of matched elements to those that pass the function's test.
Animation and Effects Methods
Method Description
.animate() Perform custom animation.
.fadeIn() Display selected elements by fading them to opaque.
.hide() Hide the selected elements.
.show() Show the selected elements.
.slideUp() Hide the matched elements with a sliding motion.
.toggle() Display or hide the selected elements.

Attaching Event Handler to Existing Element click, change, blur, focus, keyup, mouseup
If you wish to attach a single event to an existing element, the jQuery methods discussed in the section will work across-browser. If you need to attach multiple events, or attach events to future DOM events, see the section below concerning the bind(), live(), delegate(), and on() methods. Note: From V1.7 forward the recommended method among these four is the on() method.
jQuery Single Methods Work Across Browsers
IE8 and earlier had a different method for adding event listeners than was used by the other browsers. Below is the JS code (calling the DOM APIs) which is needed to support all browsers, including IE8 and earlier is:
// JS Handle Click Event.
var button = document.getElementById("SubmitButton");
if (document.addEventListener) {
  // Most browsers.
  button.addEventListener('click', function() { alert('Clicked Button'); }, false);
} else {
  // IE 8 and earlier.
  button.attachEvent('onclick',function() { alert('Clicked IE Button'); });
}

<input id="SubmitButton" type="button" value="button" />


jQuery has a single model for adding particular events that works for all browsers. It is shown in the following example for the "click" event:

//jQuery Handle Click Event.
$(document).ready(function() {
   $("#SubmitButton").click(function () {
      alert("jQuery Button Click");
   });
});

<input id="SubmitButton" type="button" value="button" />


Change Event Example - Get Value of DDL Selection
The jQuery .change() method will work with all the input controls, including the select and text area. This makes it easy to get all the input changes on a page.

// jQuery Get value of DDL Selection.
$(document).ready(function() {
  $("#selBkImage").change(function () {
     alert($(this).val());
  });
});

<!-- Drop Down List is created with select statement -->
<label for="selBkImage">Drop down list is created 
     with select statement.</label>
<select id="selBkImage">
<option value="0">Optical Gray</option>
<option value="1">Pattern Gray</option>
<option value="2">Cloth Gray</option>
<option value="3">Marble Gray</option>
</select>

Event Object jQuery Event Object Properties and Methods
When an event is handled, the event is passed to the jQuery event system. A new jQuery event object is created with the normalized properties of the original event object. This allows for cross-browser consistency of the jQuery event object.

Passing the event object into jQuery allows access to the event properties and methods.

// Use mousemove event to display event properties,
// that being the X and Y coordinates of mouse position.

$(document).on("mousemove",function (e) {
   $("#myDisplay").text("X: " + e.pageX + "   Y: " + e.pageY);
}); 

<div id="myDisplay"></div>



More Powerful Event Handling Methods bind(), live(), delegate(), on()

Different methods for attaching event handlers exist in the history of jQuery. Four of the methods are covered in this section. However, from V1.7 forward the recommended method among these four is the on() method (as shown in the code above for the Event Object). The live() method was deprecated in v1.7 and will be removed in v1.9. The on() method was introduced in jQuery 1.7 and supersedes the delegate() method.

jQuery has more powerful event handling methods which allow multiple events to be attached to an element. The live(), delegate(), and on() methods can also be used to automatically attach event handlers to new elements as they are added to the DOM. There is also a corresponding detach method to stop the event handler from being attaching to new elements.

bind() and unbind()
The bind() method can attach multiple events to an element. Be sure to have the bind() inside a ready method.

// Attach multiple events to an element
$(document).ready(function() {
  $("#myDisplay").bind("mousedown mouseup",function(e) {
    alert(e.type);
  });
});

<div id="myDisplay">Click on me.</div>


The unbind() method will detach event(s) from the element. The example below detaches the click event from a button so an alert message is displayed only on the first button click.

// Unbind after the first event fires
$(document).ready(function() {
  $("#myButton").bind("click",function(e) {
    alert("I will only display on the first button click");
    $("#myButton").unbind();
  });
});

<input id="myButton" type="button" value="Click Me">


live() and die()
The live()/die() methods were introduced in jQuery 1.3. There were deprecated in v1.7 and will be removed in v1.9.

The live() method attached the event (to be used with the new elements) all the way up at the top of the DOM on the document object. This required the event bubbling to check parent elements all the way up to the document object.
  
  // Any element added with myClass will have a click event.  
  $(".myClass").live("click",myFunction);
  
  
  // Stop future element from automatically getting event.
  $(".myClass").die("click",myFunction);
  


delegate() and undelegate()
The delegate()/undelegate() methods were introduced in jQuery 1.4. There were superseded by the on()/off() methods in jQuery 1.7.


The delegate() method was a more efficient replacement for the live() method. This method designated a parent element (delegate) where the event would be attached. New elements would only have to bubble up to the delegate element, and not have to bubble all the way up to the document object as they did with the live() method.
 
// Any element added with myClass will have a click event.  
$("#myDivs").delegate(".myClass","click", myFunction);
  


on() and off()
The on()/off() methods were introduced in jQuery 1.7 and supersedes the live()/die() methods. The on() method is the recommended method for attaching event handlers for jQuery 1.7 forward.

The on() method can work like the bind(), live(), and delegate(), depending on how it is called:
 
// bind()
$( "#myId" ).on( "click", function( e ) {} ); 
$( "#myId" ).bind( "click", function( e ) {} );  

// live()
$( document ).on( "click", "#myId", function( e ) {} ); 
$( "#myId" ).live( "click", function( e ) {} ); 

// delegate()
$( "#myId" ).on( "click", ".myClass", function( e ) {} ); 
$( "#myId" ).delegate( ".myClass", "click", function( e ) {} );

  

Cloning Code and Events clone(), on()
The following example uses jQuery to clone a DDL and a text box (defined in HTML) and copy it with the associated event handler, when a button is pressed. When the Add Phone number button is pressed, a new set of controls is displayed to accept a new telephone type and number. The new phone text box will only accept number and hyphens due to the logic in the event handler which is also automatically created with the cloned code.

$(document).ready(function() {

   var PhoneDiv= $('#PhoneDiv');

   // Handle button click
   $("#AddPhoneBtn").click(function() {
      // Clone the code with event handler attached.
      var phoneInputsDiv = $("div:eq(0)", PhoneDiv).clone();
      $("select", phoneInputsDiv).val("");
      $("input", phoneInputsDiv).val("");
      PhoneDiv.append('<span>Additional Telephone Number</span>')
               .append(phoneInputsDiv);            
   });

   // on() acting as delegate() bubbles up to PhoneDiv
   PhoneDiv.on("keypress","input", function(e) {
      // accept nothing but 0..9 and hyphen
      if (((e.keyCode < 48) || (e.keyCode > 57)) && e.keyCode != 45) {
         e.stopPropagation();
         return false;
      }   
   });
});   

<input type="button" id="AddPhoneBtn" value="Add Another Phone">
<div id="PhoneDiv"> <div> <select> <option value="">Select Phone Type</option> <option value="H">Home</option> <option value="O">Office</option> <option value="C">Cell</option> </select> <input type="text" maxlength="12" placeholder="123-456-7890"> </div> </div>


Top | Hierarchy Selectors | Extension Selectors | Input Controls | Methods | Simple Events | Advanced Events