All notes


An intro example:

<!DOCTYPE html>
<script src=""></script>
// Shorter version for $(document).ready(). See below for why using it:
		$(this).hide(); // Remember the ';' here.

<p>If you click on me, I will disappear.</p>
<p>Click me away!</p>
<p>Click me too!</p>


Why should always wrap js into document.ready event callback

w3schools. All jQuery methods should be inside a document ready event, to prevent any jQuery code from running before the document is finished loading (is ready).

// Shorter version.
   // jQuery methods go here...

   // jQuery methods go here...

Send a JSON object using html form data:

var formData = JSON.stringify($("#myForm").serializeArray());

  type: "POST",
  url: "serverUrl",
  data: formData,
  success: function(){},
  dataType: "json",
  contentType : "application/json"


The jQuery library contains the following features:

One big advantage of using the hosted jQuery from Google or Microsoft:
Many users already have downloaded jQuery from Google or Microsoft when visiting another site. As a result, it will be loaded from cache when they visit your site, which leads to faster loading time. Also, most CDN's will make sure that once a user requests a file from it, it will be served from the server closest to them, which also leads to faster loading time.


Zepto is a minimalist JavaScript library for modern browsers with a largely jQuery-compatible API. If you use jQuery, you already know how to use Zepto.

Replacing JQuery with vanillaJS

// JQuery
// Vanilla
var d = document.getElementById("div1");
d.classList.add("otherclass"); // This is prefered. Not supported in IE, but has a polyfill.
d.className += " otherclass"; // Note the space.

// JQuery
// Vanilla
// innerText is non-standard and textContent is standardized.
// <span>Hello <span style="display: none;">World</span></span>, innerText will return 'Hello', while textContent will return 'Hello World'.

// JQuery
// Vanilla


Language references


How to add html

this.$fixture = $([
  "  <div class='js-alert-box'></div>",
  "  <form id='my-form-to-validate'>",
  "    <input id='login-username' name='login-username'>",
  "  </form>",

for, each

var obj = {
  name: "Pete",
  age: 15
// Method 1: vanillaJS
for( key in obj ) {
  alert( "key is " + [ key ] + ", value is " + obj[ key ] );
// wcfNote: if obj is the jQuery wrapper, key will be a member variable list, which is not what we want.
// Method 2: jQuery each
var x = [ 1, 2, 3 ];
jQuery.each( x, function( index, value ) {
  console.log( "index", index, "value", value );


See reference for a full list.

$("*") 	Selects all elements
$(this) 	Selects the current HTML element
$("#lastname") 	The element with id="lastname"
$(".intro,.demo") 	All elements with the class "intro" or "demo"
$("p.intro") 	Selects all <p> elements with class="intro"
$("h1,div,p") 	All <h1>, <div> and <p> elements

$("div > p") 	All <p> elements that are a direct child of a <div> element
$("div p") 	All <p> elements that are descendants of a <div> element
$("div + p") 	The <p> element that are next to each <div> elements
$("div ~ p") 	All <p> elements that are siblings of a <div> element

Notice the difference below:
$("ul li:first") 	Selects the first <li> element of the first <ul>
$("ul li:first-child") 	Selects the first <li> element of every <ul>
$("p:first") 	The first <p> element
$("p:last") 	The last <p> element
$("tr:even") 	Selects all even <tr> elements
$("tr:odd") 	Selects all odd <tr> elements
$("p:first-child") 	All <p> elements that are the first child of their parent
$("p:nth-child(2)") 	All <p> elements that are the 2nd child of their parent
$("p:last-child") 	All <p> elements that are the last child of their parent
$("p:first-of-type") 	All <p> elements that are the first <p> element of their parent
$("p:nth-of-type(2)") 	All <p> elements that are the 2nd <p> element of their parent
$("p:nth-last-of-type(2)") 	All <p> elements that are the 2nd <p> element of their parent, counting from the last child
$("p:only-child") 	All <p> elements that are the only child of their parent
$("p:only-of-type") 	All <p> elements that are the only child, of its type, of their parent

$("[href]") 	Selects all elements with an href attribute
$("a[target='_blank']") 	Selects all <a> elements with a target attribute value equal to "_blank"
$("a[target!='_blank']") 	Selects all <a> elements with a target attribute value NOT equal to "_blank"
$("[href$='.jpg']") 	All elements with a href attribute value ending with ".jpg"
$("[title|='Tomorrow']") 	All elements with a title attribute value equal to 'Tomorrow', or starting with 'Tomorrow' followed by a hyphen
$("[title^='Tom']") 	All elements with a title attribute value starting with "Tom"
$("[title~='hello']") 	All elements with a title attribute value containing the specific word "hello"
$("[title*='hello']") 	All elements with a title attribute value containing the word "hello"

$("ul li:eq(3)") 	The fourth element in a list (index starts at 0)
$("ul li:gt(3)") 	List elements with an index greater than 3
$("ul li:lt(3)") 	List elements with an index less than 3

$(":header") 	All header elements <h1>, <h2> ...
$(":animated") 	All animated elements
$(":focus") 	The element that currently has focus
$(":contains('Hello')") 	All elements which contains the text "Hello"
$("div:has(p)") 	All <div> elements that have a <p> element
$(":empty") 	All elements that are empty
$(":parent") 	All elements that are a parent of another element
$("input:not(:empty)") 	All input elements that are not empty
$("table:visible") 	All visible tables

$(":input") 	All input elements
$(":text") 	All input elements with type="text"
$(":password") 	All input elements with type="password"
$(":radio") 	All input elements with type="radio"
$(":checkbox") 	All input elements with type="checkbox"
$(":submit") 	All input elements with type="submit"
$(":reset") 	All input elements with type="reset"
$(":button") 	All input elements with type="button"
$(":image") 	All input elements with type="image"
$(":file") 	All input elements with type="file"
$(":enabled") 	All enabled input elements
$(":disabled") 	All disabled input elements
$(":selected") 	All selected input elements
$(":checked") 	All checked input elements

// Combined:

Select elements with same ID

<div id="red">1</div>
<div id="green">2</div>
<div id="red">3</div>
<div id="green">4</div>
<div id="red">5</div>
<div id="green">6</div>

// Usuallly we use simple ‘#’ with id like this:
// Only make first div red and first div green and dont do anything with other elements.
$(function() {
 $('#red').css('background-color', 'red');
 $('#green').css('background-color', 'green');

// This works: all red id div to red and green id div to green color.
$(function() {
 $('[id="red"]').css('background-color', 'red');
 $('[id="green"]').css('background-color', 'green');

Radio buttons on change

stackOverflow: jquery if radio button is checked.

var appended = $('<div />').text("You're appendin'!"); = 'appended';

  function() {
    // checks that the clicked radio button is the one of value 'Yes'
    // the value of the element is the one that's checked (as noted by @shef in comments)
    if ($(this).val() == 'Yes') {
      // appends the 'appended' element to the 'body' tag
    else {
      // if it's the 'No' button removes the 'appended' element.


Some common DOM events:

// To assign a click event to all paragraphs on a page, you can do this:

// Define what should happen when the event fires:
  // action goes here!!

	$(this).css("background-color", "#cccccc");

// Attach multiple event handlers:
	mouseenter: function(){
		$(this).css("background-color", "lightgray");
	mouseleave: function(){
		$(this).css("background-color", "lightblue");
	click: function(){
		$(this).css("background-color", "yellow");

<input id='wcf' type=checkbox></input>
<div id="res"></div>

prop() doesnot trigger change event


// You need to use .change() or .trigger("change") after changing the property:
$('input[type="checkbox"][name="something"]').prop("checked", false).change();


What if other JavaScript frameworks also use the $ sign as a shortcut?

// Use jQuery instead.
		jQuery("p").text("jQuery is still working!");

// Use an alias.
var jq = $.noConflict();
		jq("p").text("jQuery is still working!");

// '$' is still workable inside.
		$("p").text("jQuery is still working!");


jquery API: types.


// Appends <b>hello</b>:
$( "<b>hello</b>" ).appendTo( "body" );
// Appends <b>hello</b>:
$( "<b>hello</b>bye" ).appendTo( "body" );
// Syntax error, unrecognized expression: bye<b>hello</b>
$( "bye<b>hello</b>" ).appendTo( "body" );
// Appends bye<b>hello</b>:
$( $.parseHTML( "bye<b>hello</b>" ) ).appendTo( "body" );
// Appends <b>hello</b>wait<b>bye</b>:
$( "<b>hello</b>wait<b>bye</b>" ).appendTo( "body" );


parseInt( "123" ) = 123 // (implicit decimal)
parseInt( "010" ) = 8 // (implicit octal)
parseInt( "0xCAFE" ) = 51966 // (implicit hexadecimal)
parseInt( "010", 10 ) = 10 // (explicit decimal)
parseInt( "11", 2 ) = 3 // (explicit binary)
parseFloat( "10.10" ) = 10.1

// Note the use of parenthesis:
"" + 1 + 2; // "12"
"" + ( 1 + 2 ); // "3"
"" + 0.0000001; // "1e-7"
parseInt( 0.0000001 ); // 1 (!)

parseInt( "hello", 10 ) // NaN
1 / 0 // Infinity
typeof NaN // "number"
typeof Infinity // "number"
NaN === NaN // false (!)
// But:
Infinity === Infinity // true


var x = [ 0, 3, 1, 2 ];
x.reverse()      // x = [ 2, 1, 3, 0 ]
x.join(" – ")    // Output: "2 - 1 - 3 - 0"
x.pop()          // x = [ 2, 1, 3 ]
x.unshift( -1 )  // Output: 4. x = [ -1, 2, 1, 3 ]
x.shift()        // Output: -1. x = [ 2, 1, 3 ]
x.sort()         // x = [ 1, 2, 3 ]
x.splice( 1, 2 ) // Output: [ 2, 3 ]. x = [1]. // The splice(index, howmany, item1, ...) method adds/removes items to/from an array, and returns the removed item(s).



jQuery(html), create elements

jQuery( html [, ownerDocument ] )
jQuery( html, attributes )

//---------- Examples

$( "<p id='test'>My <em>new</em> text</p>" ).appendTo( "body" );

function output(str) {
  var par = $('<p></p>').text(str);

// To ensure cross-platform compatibility, the snippet must be well-formed. Tags that can contain other elements should be paired with a closing tag:
$( "<a href=''></a>" );
// Tags that cannot contain elements may be quick-closed or not:
$( "<img>" );
$( "<input>" );

$( "<div/>", {
  "class": "test",
  text: "Click me!",
  click: function() {
    $( this ).toggleClass( "test" );
  .appendTo( "body" );


.each( function )

.each( function );
// Function( Integer index, Element element )
// Element:

Whenever you call jQuery's .each() method or one of its event methods on a jQuery collection, the context of the callback function "this" is set to a DOM element.

$( "input[type='text']" ).on( "blur", function() {
  if( !this.value ) { // this is DOM element.
    alert( "Please enter some text!" );

$('p.test').each(function(idx, item){
  output(item); // item is DOM element.


.first(), .last()

Reduce the set of matched elements to the first/last in the set.


Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element.

$( "li" ).has( "ul" ).css( "background-color", "red" );
// The result of this call is a red background for a "li" which has a <ul> among its descendants.

.slice(start [, end ] )

$( "li" ).slice( 2, 4 ).css( "background-color", "red" );
// Now only items 3 and 4 are selected.


Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.

$( "ul" ).click(function( event ) {
  var target = $( );
  if ( "li" ) ) {
    target.css( "background-color", "red" );


Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.

wcfNote: then you need to use .has() to check for element existence, rather than .includes() (which is for JS Array). Or you can use .get() to get.

$( ":checkbox" )
  .map(function() {

Tree traversal


For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

.closest() begins with the current element, while .parents() begins with the parent element.


Event Handler attachment

.on(), .off() off. Remove an event handler.

.off( events [, selector ] [, handler ] )

Type: String
One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin".

$( "#dataTable tbody tr" ).on( "click", function() {
  console.log( $( this ).text() );
Attaching click event to a JQuery object not yet added to the DOM


// You can replace body with any parent element that exists on dom ready.
$('body').on('click', '#my-button', function () {
  console.log("yeahhhh!!! but this doesn't work for me :(");
Custom event in jQuery that isn't bound to a DOM element?


// In YUI, this creates an event that is bound to a variable, not to a DOM element:
var myevent = new YAHOO.util.CustomEvent("mycustomevent");

// You can trigger custom global events like this in jQuery, These will trigger for any element:
jQuery.event.trigger('mycustomevent', [arg1, arg2, arg3]);
// You can bind your event to a global DOM object if you don't want to bind it to an individual page element:
$(document).bind('mycustomevent', function (e, arg1, arg2, arg3) { /* ... */ });

one() one.

Attach a handler to an event for the elements. The handler is executed at most once per element per event type.

stackOverflow. one() function is automatically moved to off state after first instance of occurance. on() is identical to one() but it needs to be manually put to off state otherwise the number of instances has no limit.

var i = 1;
$('.one').one('click', function() {
  $(this).text('I am clickable only once: ' + i);

var j = 1;
$('.multiple').on('click', function() {
  $(this).text('I was clicked ' + j + ' times');


DOM Element Methods


Retrieve the DOM elements matched by the jQuery object.

  <li id="foo">foo</li>
  <li id="bar">bar</li>

// Without a parameter, .get() returns an array of all of the elements:
console.log( $( "li" ).get() );
// [<li id="foo">, <li id="bar">] 


map() map.

The map() method applies a function to each item in an array or object and maps the results into a new array.

var arr = [ "a", "b", "c", "d", "e" ];
arr = arr, function( n, i ) {
  return ( n.toUpperCase() + i );
// [ "A0", "B1", "C2", "D3", "E4" ]


You might want to know what event handlers are attached to a certain element or an object. You can do that with the $._data() method.

var $btn = $('#some-button-id');
$btn.on('click', function() {
  console.log('click handler');
$btn.on('mouseover', function() {
  console.log('mouseover handler');

$._data($btn, "events");
// Outputs to console:
// Object {click: Array[1], mouseover: Array[1]}

// In older versions of jQuery (prior version 1.8) you can use the following:
Notice that the new method is not public or at least not intended to be public, i.e. it has an underscore in it’s name. That means that it’s not advisable to use it in production code. But as I said before it may be useful for debugging purposes.

addClass(), removeClass()

// Switch elements' classes from one to another
$( "p" ).removeClass( "myClass noClass" ).addClass( "yourClass" );

// As of jQuery 1.4, the .addClass() method's argument can receive a function.
$( "ul li" ).addClass(function( index ) {
  return "item-" + index; // E.g. add "item-0" to the first list item.

// Calling removeClass with no parameters will remove all of the item's classes.
// If you didn't have jQuery, then this would be pretty much your only option:
document.getElementById('item').className = '';


.change( handler );
.change( [eventData ], handler );
// This method is a shortcut for .on( "change", handler ) in the first two variations, and .trigger( "change" ) in the third.


// Add change() so that the change event is triggered!
if (new_quantity >= 1) {

children() children.

The .children() method differs from .find() in that .children() only travels a single level down the DOM tree while .find() can traverse down multiple levels to select descendant elements (grandchildren, etc.) as well.

Note also that like most jQuery methods, .children() does not return text nodes; to get all children including text and comment nodes, use .contents().

$( "div" ).children( ".selected" ).css( "color", "blue" );

clone() clone.

It performs a deep copy of the set of matched elements, meaning that it copies the matched elements as well as all of their descendant elements and text nodes.

$( ".hello" ).clone().appendTo( ".goodbye" );

// This would produce:
<div class="container">
  <div class="hello">Hello</div>
  <div class="goodbye">
    <div class="hello">Hello</div>


// First retrieves the contents of ".container" and then filters it for text nodes (nodtType == 3), which are wrapped in paragraph tags. The contents are again filtered, this time for <br /> elements, and these elements are removed.
$( ".container" )
    .filter(function() {
      return this.nodeType === 3;
      .wrap( "<p></p>" )
    .filter( "br" )


// You can use .css() to remove css property as well, like this:
// Setting the value of a style property to an empty string removes that property from an element if it has already been directly applied:

data(), removeData()

Store arbitrary data associated with the matched elements or return the value at the named data store for the first element in the set of matched elements.

// We can set several distinct values for a single element and retrieve them later:
$( "body" ).data( "foo", 52 );
$( "body" ).data( "bar", { myType: "test", count: 40 } );
$( "body" ).data( { baz: [ 1, 2, 3 ] } );
$( "body" ).data( "foo" ); // 52
$( "body" ).data(); // { foo: 52, bar: { myType: "test", count: 40 }, baz: [ 1, 2, 3 ] }
// Prior to jQuery 1.4.3 (starting in jQuery 1.4) the .data() method completely replaced all data, instead of just extending the data object.

$( "div" ).removeData( "test1" );
// Note that .removeData() will only remove data from jQuery's internal .data() cache, and any corresponding data- attributes on the element will not be removed. A later call to data() will therefore re-retrieve the value from the data- attribute. To prevent this, use .removeAttr() alongside .removeData() to remove the data- attribute as well.

data-* attributes

As of jQuery 1.4.3 HTML 5 data- attributes will be automatically pulled in to jQuery's data object. The treatment of attributes with embedded dashes was changed in jQuery 1.6 to conform to the W3C HTML5 specification.

<div data-role="page" data-last-value="43" data-hidden="true" data-options='{"name":"John"}'></div>

// All of the following jQuery code will work.
$( "div" ).data( "role" ) === "page";
$( "div" ).data( "lastValue" ) === 43;
$( "div" ).data( "hidden" ) === true;
$( "div" ).data( "options" ).name === "John";

//---------- attr() also works:


// For
// <div data-test="lala">asdf</div>

alert($('div').data('test')); // lala
var t = 'data-test2';
var v = 'hiho';
alert($('div').data('test2')); // hiho
alert($('div').attr('data-test2')); // hiho


$( "li.item-ii" ).find( "li" ).css( "background-color", "red" );

// If we need to retrieve all of the descendant elements, we can pass in the universal selector '*' to accomplish this.
$( "li.item-ii" ).find( "*" ).css( "background-color", "red" );
// $( "li.item-ii" ).find( "li" ) is equivalent to $( "li", "li.item-ii" ).

getScript() getScript.

The script is executed in the global context, so it can refer to other variables and use jQuery functions. Included scripts can have some impact on the current page.

jQuery.getScript( url [, success ] );
// This is a shorthand Ajax function, which is equivalent to:
  url: url,
  dataType: "script",
  success: success

get() get.

console.log( $( "li" ).get( 0 ) );
// Same as:
console.log( $( "li" )[ 0 ] );

function display( divs ) {
  var a = [];
  for ( var i = 0; i < divs.length; i++ ) {
    a.push( divs[ i ].innerHTML );
  $( "span" ).text( a.join(" ") );
display( $( "div" ).get().reverse() );

<!-- Output in HTML:
Reversed - Three Two One

html(), text()

$('div#res').text($('input#wcf').prop('checked')); // When prop('checked') is false, it outputs "false."
$('div#res').html($('input#wcf').prop('checked')); // When prop('checked') is false, it outputs "" (nothing!)

jquery(), \$()

jQuery( selector [, context ] )
jQuery( html [, ownerDocument ] )
jQuery( callback )

// The third format: Execute the function when the DOM is ready to be used.
$(function() {
  // Document is ready

// Define a plain object
var foo = { foo: "bar", hello: "world" };
// Pass it to the jQuery function
var $foo = $( foo );
// Test accessing property values
var test1 = $foo.prop( "foo" ); // bar
// Test setting property values
$foo.prop( "foo", "foobar" );
var test2 = $foo.prop( "foo" ); // foobar

// The use of .data() (or any method requiring .data()) on a plain object will result in a new property on the object called jQuery{randomNumber} (eg. jQuery123456789).
// Test using .data() as summarized above
$ "keyName", "someValue" );
console.log( $foo ); // will now contain a jQuery{randomNumber} property
// Test binding an event name and triggering
$foo.on( "eventName", function () {
  console.log( "eventName was called" );
$foo.trigger( "eventName" ); // Logs "eventName was called"

// Find all p elements that are children of a div element and apply a border to them.
$( "div > p" ).css( "border", "1px solid gray" );
// Find all inputs of type radio within the first form in the document.
$( "input:radio", document.forms[ 0 ] );

//---------- Create a new DOM element with HTML
$( "<p id='test'>My <em>new</em> text</p>" ).appendTo( "body" );

//---------- Create

$( "<div></div>", {
  // The name "class" must be quoted in the object since it is a JavaScript reserved word, and "className" cannot be used since it refers to the DOM property, not the attribute.
  "class": "my-div",
  on: {
    touchstart: function( event ) {
      // Do something
}).appendTo( "body" );

$( "<div></div>" )
  .addClass( "my-div" )
    touchstart: function( event ) {
      // Do something
  .appendTo( "body" );


Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.

It retrieves the current position of an element (specifically its margin box) relative to the offset parent (specifically its padding box, which excludes margins and borders). position.


jqueryAPI. Encode a set of form elements as an array of names and values.

$( "form" ).submit(function( event ) {
  console.log( $( this ).serializeArray() );
  // Prevent the default event effect.

Convert form data to JavaScript object with jQuery

<form action="" method="post">
First Name:<input type="text" name="Fname" maxlength="12" size="12"/> <br/>
Last Name:<input type="text" name="Lname" maxlength="36" size="12"/> <br/>
Male:<input type="radio" name="gender" value="Male"/><br/>
Female:<input type="radio" name="gender" value="Female"/><br/>
Favorite Food:<br/>
Steak:<input type="checkbox" name="food[]" value="Steak"/><br/>
Pizza:<input type="checkbox" name="food[]" value="Pizza"/><br/>
Chicken:<input type="checkbox" name="food[]" value="Chicken"/><br/>
<textarea wrap="physical" cols="20" name="quote" rows="5">Enter your favorite quote!</textarea><br/>
Select a Level of Education:<br/>
<select name="education">
<option value="Jr.High">Jr.High</option>
<option value="HighSchool">HighSchool</option>
<option value="College">College</option></select><br/>
Select your favorite time of day:<br/>
<select size="3" name="TofD">
<option value="Morning">Morning</option>
<option value="Day">Day</option>
<option value="Night">Night</option></select>
<p><input type="submit" /></p>
<pre id="result">

$.fn.serializeObject = function()
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[] !== undefined) {
            if (!o[].push) {
                o[] = [o[]];
            o[].push(this.value || '');
        } else {
            o[] = this.value || '';
    return o;

$(function() {
    $('form').submit(function() {
        return false;



//---------- Three methods
// jQuery 1.6+
// jQuery 1.5 and below
// Any version of jQuery
// Assuming an event handler on a checkbox
if (this.checked) {};

//---------- Using jQuery > 1.6
// traditional attr
$('#checkMeOut').attr('checked'); // "checked"
// new property method
$('#checkMeOut').prop('checked'); // true

if(document.getElementById('isAgeSelected').checked) {
} else {

// Much prettier way to do the same:
$('#isAgeSelected').click(function() {

// Or

//---------- Toggle Checkboxes on/off
var checkBoxes = $("input[name=recipients\\[\\]]");
checkBoxes.prop("checked", !checkBoxes.prop("checked"));

Get, Set

The callback function has two parameters: the index of the current element in the list of elements selected and the original (old) value.

text() - Sets or returns the text content of selected elements
html() - Sets or returns the content of selected elements (including HTML markup)
val() - Sets or returns the value of form fields
attr() - get attribute values.

	alert("Text: " + $("#test").text());
	alert("HTML: " + $("#test").html());
	alert("Value: " + $("#test").val());

// Callback function for setting.
	$("#test1").text(function(i, origText){
		return "Old text: " + origText + " New text: Hello world!
		(index: " + i + ")";

	$("#test2").html(function(i, origText){
		return "Old html: " + origText + " New html: Hello world!
		(index: " + i + ")";

Effects: hide/show, toggle, fade, slide, animate

// Toggles between the fadeIn() and fadeOut() methods.
// Stop animations or effects before it is finished:


    var div = $("div");
    div.animate({left: '100px'}, "slow");
    div.animate({fontSize: '3em'}, "slow");

// Chainning.
$("#p1").css("color", "red").slideUp(2000).slideDown(2000);


Unlike shorthand animation methods such as .slideDown() and .fadeIn(), the .animate() method does not make hidden elements visible as part of the effect.

Note that the target value of the height property is 'toggle'. Since the image was visible before, the animation shrinks the height to 0 to hide it. A second click then reverses this transition.

<div id="clickme">
  Click here
<img id="book" src="book.png" alt="" width="100" height="123"
  style="position: relative; left: 10px;">

// To animate the opacity, left offset, and height of the image simultaneously:
$( "#clickme" ).click(function() {
  $( "#book" ).animate({
    opacity: 0.25,
    left: "+=50",
    height: "toggle"
  }, 5000, function() {
    // Animation complete.


show() is roughly equivalent to calling .css( "display", "block" ), except that the display property is restored to whatever it was initially, e.g. "inline".

hide(): The matched elements will be hidden immediately, with no animation. This is roughly equivalent to calling .css( "display", "none" ), except that the value of the display property is saved in jQuery's data cache so that display can later be restored to its initial value.

// Same as the JS:
document.getElementById("test").style.display = "none";
// But not like
document.getElementById("test").style.visibility = "hidden";

//---------- Check if hide or show

// Checks css for display:[none|block], ignores visibility:[true|false]

// The same works with hidden

Does using display: none effectively remove the element from the DOM

Keep in mind that CSS is for style only, it does not have the ability to affect the DOM.

trigger(), on(), triggerHandler() trigger.

To trigger handlers bound via jQuery without also triggering the native event, use .triggerHandler() instead.

//---------- Definitions.
.trigger( eventType [, extraParameters ] );
// eventType. Type: String. A string containing a JavaScript event type, such as click or submit.
.trigger( event [, extraParameters ] );
// event. Type: Event. A jQuery.Event object.

//---------- on, trigger.
$( "#foo" ).on( "click", function() {
  alert( $( this ).text() );
$( "#foo" ).trigger( "click" );

//---------- custom event type.
$( "#foo" ).on( "custom", function( event, param1, param2 ) {
  console.log(event); // jQuery.Event
  alert( param1 + "\n" + param2 );
$( "#foo").trigger( "custom", [ "Custom", "Event" ] );

//---------- event namespacing
// If you want to add a single event and then remove it (without removing any others that might have been added) then you can use event namespacing:
$('#myimage').on('click.mynamespace', function() { /* Do stuff */ });

prop(), attr() prop.

.prop( propertyName )
.prop( propertyName, value )

prop vs attr

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.

The most important concept to remember about the "checked attribute" is that it does not correspond to the "checked property". The attribute actually corresponds to the "defaultChecked" property and should be used only to set the initial value of the checkbox. The checked attribute value does not change with the state of the checkbox, while the checked property does.


The "checked" attribute does not correspond to the "checked" property. The attribute actually corresponds to the "defaultChecked" property and should be used only to set the initial value of the checkbox. The checked attribute value does not change with the state of the checkbox, while the checked property does.

<input id="check1" type="checkbox" checked="checked">
<label for="check1">Check me</label>
$( "input" ).change(function() {
  var $input = $( this );
  $( "p" ).html(
    ".attr( \"checked\" ): <b>" + $input.attr( "checked" ) + "</b><br>" +
    ".prop( \"checked\" ): <b>" + $input.prop( "checked" ) + "</b><br>" +
    ".is( \":checked\" ): <b>" + $ ":checked" ) + "</b>" );

$("input").prop("checked", true);
<!-- $input.attr( "checked" ) will always be "checked". The other two will be true/false according to the checked status. -->


Get the current value of the first element in the set of matched elements or set the value of every matched element.

// Get the value from a checked checkbox
$( "input[type=checkbox][name=bar]:checked" ).val();
// Get the value from a set of radio buttons
$( "input[type=radio][name=baz]:checked" ).val();

// Will make the value to upper case.
$( "input" ).on( "blur", function() {
  $( this ).val(function( i, val ) {
    return val.toUpperCase();

//---------- Recommed to use prop() instead of val().
// Check #x
$( "#x" ).prop( "checked", true );
// Uncheck #x
$( "#x" ).prop( "checked", false );

Set select checked

val() allows you to pass **an array of element values**. This is useful when working on a jQuery object containing elements like <input type="checkbox">, <input type="radio">, and <option>s inside of a <select>. In this case, the inputs and the options having a value that matches one of the elements of the array will be checked or selected while those having a value that doesn't match one of the elements of the array will be unchecked or unselected, depending on the type. In the case of <input type="radio">s that are part of a radio group and <select>s, any previously selected element will be deselected.

Setting values using this method (or using the native value property) does not cause the dispatch of the change event. For this reason, the relevant event handlers will not be executed. If you want to execute them, you should call .trigger( "change" ) after setting the value.


<!-- ---------- Example from JQuery -->
<!-- -->
<select id="single">
<select id="multiple" multiple="multiple">
  <option selected="selected">Multiple</option>
  <option selected="selected">Multiple3</option>
<input type="checkbox" name="checkboxname" value="check1"> check1
<input type="checkbox" name="checkboxname" value="check2"> check2
<input type="radio" name="r" value="radio1"> radio1
<input type="radio" name="r" value="radio2"> radio2
$( "#single" ).val( "Single2" ); <!-- Here we set value on "select", but not "option". If we set values on "option", it will change the "value" attributes instead!!! -->
$( "#multiple" ).val([ "Multiple2", "Multiple3" ]);
$( "input").val([ "check1", "check2", "radio1" ]); <!-- Here we set value on "input". -->

<!-- ---------- Example: set value on inputs  -->

<input type="radio" name="test" checked value="a" />
<input type="radio" name="test" value="b" />
$(function() {
	$('[name="test"]').val(['a']); // Here you must give an array!

<!-- ---------- Example: set value on selects  -->

<div class="id_100">
    <option value="val1">Val 1</option>
    <option value="val2">Val 2</option>
    <option value="val3">Val 3</option>

$("div.id_100 select").val("val2"); // Here a value just works.


$.ajax({name:value, name:value, ... })

AJAX = Asynchronous JavaScript and XML. Without jQuery, AJAX coding can be a bit tricky: different browsers have different syntax for AJAX implementation.


Loads data from a server and puts the returned data into the selected element.


// Loads the content of the element with id="p1":
$("#div1").load("demo_test.txt #p1");

// responseTxt - contains the resulting content if the call succeeds
// statusTxt - contains the status of the call
// xhr - contains the XMLHttpRequest object
	$("#div1").load("demo_test.txt", function(responseTxt, statusTxt, xhr){
		if(statusTxt == "success")
			alert("External content loaded successfully!");
		if(statusTxt == "error")
			alert("Error: " + xhr.status + ": " + xhr.statusText);



	$.get("demo_test.asp", function(data, status){
		alert("Data: " + data + "\nStatus: " + status);

		name: "Donald Duck",
		city: "Duckburg"
	function(data, status){
		alert("Data: " + data + "\nStatus: " + status);



  type: "GET",
  url: "index1.php",
  dataType: 'json',
  async: false,
  username: username,
  password: password,
  data: '{ "comment" }',
  success: function (){
    alert('Thanks for your comment!'); 

// Preemptive method:
  type: "GET",
  url: "index1.php",
  dataType: 'json',
  async: false,
  headers: {
    "Authorization": "Basic " + btoa(USERNAME + ":" + PASSWORD)
  data: '{ "comment" }',
  success: function (){
    alert('Thanks for your comment!'); 

Ajax success data shown as [object object]?

alert() prints the string representation of the arguments - hence if you pass an object, you'll get [object Object].
To inspect data, use console.log(data) better. StackOverflow.

	type: "GET",
	url: "https://"+window.document.location.hostname+":443/accounts/"+$("#username").val(),
	username: $("#username").val(),
	password: $("#password").val(),
	success: function(data, status, xhr){
		// The following will show [object object]:
		// $("#res").text(returnedData)
	dataType: "json",
	contentType : "application/json"

Prettify json output with javascript

JSFiddle. StackOverflow.

// Simplest version:
var jsonString = '{"some":"json"}';
var jsonPretty = JSON.stringify(JSON.parse(jsonString),null,2);

// Advanced version:
function syntaxHighlight(json) {
	if (typeof json != 'string') {
		 json = JSON.stringify(json, undefined, 2);
	json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
	return json.replace(/("(\u[a-zA-Z0-9]{4}|\[^u]|[^\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
		var cls = 'number';
		if (/^"/.test(match)) {
			if (/:$/.test(match)) {
				cls = 'key';
			} else {
				cls = 'string';
		} else if (/true|false/.test(match)) {
			cls = 'boolean';
		} else if (/null/.test(match)) {
			cls = 'null';
		return '<span class="' + cls + '">' + match + '</span>';


AJAX examples

Form submitting

SO: jquery ajax submitting form.

Submitting JSON

css-tricks provides a customized serializeObject function.

<form id="contactForm1" action="/your_url" method="post">

<script type="text/javascript">
    // Serialize form to json.
    $.fn.serializeObject = function()
       var o = {};
       var a = this.serializeArray();
       $.each(a, function() {
           if (o[]) {
               if (!o[].push) {
                   o[] = [o[]];
               o[].push(this.value || '');
           } else {
               o[] = this.value || '';
       return o;

    var frm = $('#contactForm1');
    frm.submit(function (ev) {
            type: frm.attr('method'),
            url: frm.attr('action'),
            data: JSON.stringify(frm.serializeObject()),
            success: function (data) {
            dataType: "json",
            contentType : "application/json"

        // Prevent the current page being directed to form action URL.

Instead of return false you should be using e.preventDefault() to allow further event propagation after your click handler is complete. Using e.preventDefault() will only stop the default action of the Submit button (e.g. to submit the form) but will allow any other events bound to that form to execute.

SO: post JSON with jquery.

When you pass an object, jQuery uses $.param to serialize the object into name-value pairs. If you pass the data as a string, it won't be serialized:

    type: 'POST',
    url: '/form/',
    // Without the surrounding quotes, you're passing an object, not a JSON string:
    // data: {"name":"jonas"},
    data: '{"name":"jonas"}',
    // or:
    // JSON.stringify ({name: 'jonas'}),
    success: function(data) { alert('data: ' + data); },
    contentType: "application/json",
    dataType: 'json'

Handle with XML


Response XML:

<?xml version="1.0" encoding="UTF-8"?>
<response status="ok">

  type: 'GET',
  url: "foo.aspx",
  data: {
    key: "value"
  dataType: "xml",
  success: function (xml){
    var clientid = $(xml).find('client_id').first().text();


Success callback never called when posting JSON

csdn: Jquery ajax json 不执行success的原因

Phenomenon: 如果指定了dataType为json,老是不执行success回调,而是执行了error回调函数。只有小于1.3版本的jQuery才能执行success回调。 API ajax:

The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead.

原来返回的是{success:true,id:1} 这种不规则的字符串,不是严格的json格式,改成{"success":true,"id":"1"} 就可以正常执行success回调了。

Deferred jquery.deferred.

Why we need it

The usual ajax way:

  url: "/echo/json/",
  data: {json: JSON.stringify({firstName: "Jose", lastName: "Romaniello"})} ,
  type: "POST",
  success: function(person){
    alert(person.firstName + " saved."); 
  error: function(){ 

This works but it is not an standard interface, it requires some work inside the post method and we can't register multiple callbacks.


A factory function that returns a chainable utility object (Deferred Object) with methods to register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function.

A Deferred object starts in the pending state. Any callbacks added to the object with deferred.then(), deferred.always(), deferred.done(), or are queued to be executed later.

Calling deferred.resolve() or deferred.resolveWith() transitions the Deferred into the resolved state and immediately executes any doneCallbacks that are set. Calling deferred.reject() or deferred.rejectWith() transitions the Deferred into the rejected state and immediately executes any failCallbacks that are set.

Once the object has entered the resolved or rejected state, it stays in that state. Callbacks can still be added to the resolved or rejected Deferred — they will execute immediately.

var deferred = $.Deferred();
deferred.then(function(value) {
  return 42;
  alert('The answer : ' + id);

deferred.resolve("hello world");

// Will first alert "hello world", then alert "The answer : 42".


var loadPageViewLoaded = $.Deferred();
var loadPageEditorLoaded = $.Deferred();
asyncLoadPackage('layout_page_view').then(function(requiredModule) {
asyncLoadPackage('layout_page_edit').then(function(requiredModule) {
$.when(loadPageViewLoaded, loadPageEditorLoaded).done(function(layoutPageView, layourPageEditor) {
  console.log(layoutPageView, layourPageEditor);

deferred.always(), catch(), done(), fail(), then()

//---------- then

deferred.then( doneFilter [, failFilter ] [, progressFilter ] )

//---------- done, fail

deferred.done( doneCallbacks [, doneCallbacks ] )
// Description: Add handlers to be called when the Deferred object is resolved. failCallbacks [, failCallbacks ] )
// Description: Add handlers to be called when the Deferred object is rejected.

$.get( "test.php" )
  .done(function() {
    alert( "$.get succeeded" );
  .fail(function() {
    alert( "$.get failed!" );

// Another example
function fn1() {
  $( "p" ).append( " 1 " );
function fn2() {
  $( "p" ).append( " 2 " );
function fn3( n ) {
  $( "p" ).append( n + " 3 " + n );
// Create a deferred object
var dfd = $.Deferred();
// Add handlers to be called when dfd is resolved
  .done( [ fn1, fn2 ], fn3, [ fn2, fn1 ] )
  .done(function( n ) {
    $( "p" ).append( n + " we're done." );
// Resolve the Deferred object when the button is clicked
$( "button" ).on( "click", function() {
  dfd.resolve( "and" );
// Output: 1 2 and 3 and 2 1 and we're done.

//---------- always

deferred.always( alwaysCallbacks [, alwaysCallbacks ] );
// Call a function, or array of functions, when the Deferred is resolved or rejected.

$.get( "test.php" ).always(function() {
  alert( "$.get completed with success or error callback arguments" );

//---------- catch

deferred.catch( fn )
// An alias to deferred.then( null, fn ).

$.get( "test.php" )
  .then( function() {
    alert( "$.get succeeded" );
  } )
  .catch( function() {
    alert( "$.get failed!" );
  } );

//---------- progress, notify

// Add handlers to be called when the Deferred object generates progress notifications.
// When the Deferred generates progress notifications by calling notify or notifyWith, the progressCallbacks are called.
deferred.progress( progressCallbacks [, progressCallbacks ] )

deferred.notify( args )
// Each callback is passed the args from the .notify().
deferred.notifyWith( context [, args ] )
// context: Context passed to the progressCallbacks as the this object.


This method returns an object with almost the same interface than the Deferred(), but it only have the methods to attach callbacks and does not have the methods to resolve and reject.

This is useful when you want to give to the calling API something to subscribe to, but not the ability to resolve or reject the deferred.

The ajax() method in JQuery returns a Promise, so you can do:

var post = $.ajax({
  url: "/echo/json/",
  data: {json: JSON.stringify({firstName: "Jose", lastName: "Romaniello"})} ,
  type: "POST"

  alert(p.firstName +  " saved.");

// You can add as many callbacks as you want.


It allows you to “project” a promise.


function getCustomerSSNById(customerId){
  return $.post("/echo/json/", {
      json: JSON.stringify({firstName: "Jose", lastName: "Romaniello", ssn: "123456789"})
    return p.ssn; // Get a projection.

function getPersonAddressBySSN(ssn){
  return $.post("/echo/json/", {
      json: JSON.stringify({
        ssn: "123456789",
        address: "Siempre Viva 12345, Springfield" })
    return p.address;

function getPersonAddressById(id){
  return getCustomerSSNById(id)

    alert("The address is " + a); 

Recursive deferred

Imagine that you started an asynchronous operation in the backend, and you need to do “polling” to see if the task is done and when the task is done do something else.

//1: done, 2: cancelled, other: pending
function getPrintingStatus(){
  var d = $.Deferred();
      json: JSON.stringify( {status: Math.floor(Math.random()*8+1)} ),
      delay: 2
  return d.promise();

function pollUntilDone(){
  //do something
  return getPrintingStatus()
        if(s === 1 || s == 2) {
          return s;  //if the status is done or cancelled return the status
        //if the status is pending... call this same function
        //and return a deferred...
        return pollUntilDone();

$.blockUI({message: "Loading..."});

  .pipe(function(s){ //project the status code to a meaningfull string.
      case 1:
        return "done";
      case 2:
        return "cancelled";
    alert("The status is " + s);


The method accepts an arbitrary number of promises, and it returns a master deferred that:

The done callback has the results of all the promises.

function getCustomer(customerId){
  var d = $.Deferred();
    {json: JSON.stringify({firstName: "Jose", lastName: "Romaniello", ssn: "123456789"})}
  return d.promise();

function getPersonAddressBySSN(ssn){
  return $.post("/echo/json/", {
      json: JSON.stringify({
        ssn: "123456789",
        address: "Siempre Viva 12345, Springfield" })
    return p.address;

$.when(getCustomer(123), getPersonAddressBySSN("123456789"))
  .done(function(person, address){
    alert("The name is " + person.firstName + " and the address is " + address);

Good References 18 surprises from reading jquery's source code.