Get jQuery from:

When $ is ready?

  • document.ready
  • function
    $(function() {});
  • everywhere if we’re plugging it in on the bottom

Traversing DOM

Selectors

  • Select all elements:
    $( "*" )
  • CSS selectors, like '.' and "#":
    $(".my_class")
  • Attributes contains selector or word selector:
    
    <input name="milk man">
    <input name="milkman">
    
    <script>
    //selector
    $( "input[name*='man']" ).val( "has man in it!" );
    </script>
    
    <script>
    //word selector
    $( "input[name~='man']" ).val( "mr. man is in it!" );
    </script>
                    

More attribute-based selectors:

  • Attribute Ends With Selector [name$="value"]
  • Attribute Equals Selector [name="value"]
  • Attribute Contains Prefix Selector [name|="value"]
  • Attribute Not Equal Selector [name!="value"]
  • Has Attribute Selector [name]
  • Multiple Attribute Selector [name="value"][name2="value2"]

Hierarchy selectors

Child Selector (“parent > child”)


  • Item 1
  • Item 2
    • Nested item 1
    • Nested item 2
    • Nested item 3
  • Item 3

Descendant Selector (“ancestor descendant”)


Sibling to form:

Next Adjacent Selector (“prev + next”)


Next Siblings Selector (“prev ~ siblings”)


div (doesn't match since before #prev)
span#prev
div sibling
div sibling
div niece
span sibling (not div)
div sibling

Extension for CSS selectors


  $( ":input" )
  $( ":button" )
  $( ":checkbox" )
  $( ":file" )
  $( ":password" )
  $( ":text" )
  $( ":radio" )
  $( ":reset" )
  $( "select option:selected" )
  $( ":checked" )
  $( ":disabled" )
  $( ":enabled" )
  $( ":focused" )
  $( ":submit" )

Extension for CSS selectors (continued)


 $( "div:animated" )
 $( ":first" )
 $( "tr:last" )
 $( "td:eq( 2 )" ) //Select the element at index n within the matched set.
 $( "td:gt(4)" )   //Select all, which have index > 4 within the matched set.
 $( "td:lt(4)" )   //Select all, which have index < 4 within the matched set.
 $( ":odd" )
 $( ":even" )

Extension for CSS selectors: the end is near!


 // Select all elements that have
 //at least one child node (either an element or text).
 $( "td:parent" )
 $( "div:has(p)" )
 $( ":header" ) // h1, h2, etc.
 $( ":hidden" ) // display: none, type='hidden', width&height = 0
 $( ":visible" )
 $( ":image" )
... learn more: http://api.jquery.com/category/selectors/

Traversing

Once you've made an initial selection with jQuery, you can traverse deeper into what was just selected.

Parents


// returns [ div.child ]
$( "span.subchild" ).parent();
// returns [ div.parent ]
$( "span.subchild" ).parents( "div.parent" );
// returns [ div.child, div.parent, div.grandparent ]
$( "span.subchild" ).parents();
// returns [ div.child, div.parent ]
$( "span.subchild" ).parentsUntil( "div.grandparent" );
// returns [ div.child ]
$( "span.subchild" ).closest( "div" );
// returns [ div.child ] as the selector is also included in the search:
$( "div.child" ).closest( "div" );

Children


// Selecting an element's direct children:

// returns [ div.parent, div.surrogateParent1, div.surrogateParent2 ]
$( "div.grandparent" ).children( "div" );

// Finding all elements within a selection that match the selector:

// -> [ div.child, div.parent, div.surrogateParent1, div.surrogateParent2 ]
$( "div.grandparent" ).find( "div" );
              

Siblings



// Selecting an element's siblings in both
//directions that matches the given selector:

// returns [ div.surrogateParent1, div.surrogateParent2 ]
$( "div.parent" ).siblings();

// returns [ div.parent, div.surrogateParent2 ]
$( "div.surrogateParent1" ).siblings();

 // Selecting a next sibling of the selectors:
 // returns [ div.surrogateParent1 ]
$( "div.parent" ).next();

 // Selecting a prev sibling of the selectors:
 // returns [] as No sibling exists before div.parent
$( "div.parent" ).prev();

Siblings (continued)


// Selecting all the next siblings of the selector:
// returns [ div.surrogateParent1, div.surrogateParent2 ]
$( "div.parent" ).nextAll();
// returns [ div.surrogateParent1 ]
$( "div.parent" ).nextAll().first();
// returns [ div.surrogateParent2 ]
$( "div.parent" ).nextAll().last();

// Selecting all the previous siblings of the selector:
// returns [ div.surrogateParent1, div.parent ]
$( "div.surrogateParent2" ).prevAll();
// returns [ div.surrogateParent1 ]
$( "div.surrogateParent2" ).prevAll().first();
// returns [ div.parent ]
$( "div.surrogateParent2" ).prevAll().last();

Chaining


// No chaining
$("#menu").fadeIn("fast");
$("#menu").addClass(".active");
$("#menu").css("marginRight", "10px");

// vs. with chaining
$("#menu").fadeIn("fast")
          .addClass("active")
          .css("marginRight", "10px");
              

How? Almost all jQuery methods return a jQuery object.

Toggle


Click to toggle

highlight

on these

paragraphs

Learn more: http://api.jquery.com/toggleClass/

Changing element attributes with attr


$("button").click(function(){
  $("img").attr("width","500");
});
              

Come and try: http://jsbin.com/EbOtuVu/1/edit

Data-attributes

NOT to be confused with data-storage! jQuery introduced support for data attributes in version 1.4.3, which was released in October 2010.



$( "div" ).data( "role" ) === "page";
$( "div" ).data( "lastValue" ) === 43;
$( "div" ).data( "hidden" ) === true;
$( "div" ).data( "options" ).name === "John";

var baz = $('div').data('foobar').foo; //you can use JSON syntax, wee!

Getting styles with .css


#box1 {
    width: 50px;
    color: yellow;
    background-color: blue;
  }

1

Modifying styles



Just roll the mouse over me.

Or me to see a color change.

Form goodies

Getting values


// Get the value from a dropdown select
$( "select.foo option:selected").val();

// Get the value from a dropdown select even easier
$( "select.foo" ).val();

// Get the value from a checked checkbox
$( "input:checkbox:checked" ).val();

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

              

Try it yourself: http://jsbin.com/AmESuFOj/1/edit

.serialize

The .serialize() method creates a text string in standard URL-encoded notation.


First name:
Last name:

$("form").serialize(); //returns FirstName=Mickey&LastName=Mouse
$("form").serializeArray(); //returns an array

Try it yourself: http://jsbin.com/UhuNOHoS/1/edit

html() methods

Returns the html contents
$("p").html()
Replaces the html contents

Demonstration Box

$( "div.demo-container" )
  .html( "

All new content. You bet!

" ); //or $( "div.demo-container" ).html(function() { var emphasis = "" + $( "p" ).length + " paragraphs!"; return "

All new content for " + emphasis + "

"; });

All new content. You bet!

.text() methods

Same as .html but for plain text.

.wrap() elements around

Wrap a <div> element around each <p> element:

$("button").click(function(){
  $("p").wrap("
"); }); $("p").wrap(function(){ return "
" });

Events

DOM Events level 0

This event handling model was introduced by Netscape Navigator, and remains the most cross-browser model

Inline events

In the inline model,event handlers are added as attributes of elements.


Inline Event Handling

Hey Joe!


function triggerAlert(name) {
        window.alert("Hey " + name);
}

Traditional events


Traditional Event Handling

Hey Johny!


var triggerAlert = function () {
        window.alert("Hey Johny");
};

// Assign an event handler
document.onclick = triggerAlert;

// Assign another event handler
window.onload = triggerAlert;

// Remove the event handler that was just assigned
window.onload = null;

DOM level 2 event model

A more flexible one.

  • addEventListener: Allows the registration of event listeners on the event target.
  • removeEventListener: Allows the removal of event listeners from the event target.
  • dispatchEvent: Allows sending the event to the subscribed event listeners.
  • stopPropagation: To prevent an event from bubbling, developers must call the this method of the event object
  • preventDefault: To prevent the default action of the event to be called, developers must call the this method of the event object.

Example of DOM level 2 events


DOM Level 2

Hey Joe!


var heyJoe = function () {
     window.alert("Hey Joe!");
}

// Add an event handler
document.addEventListener( "click", heyJoe, true );  // capture phase

// Add another event handler
window.addEventListener( "load", heyJoe, false );  // bubbling phase

// Remove the event handler just added
window.removeEventListener( "load", heyJoe, false );

MS IE event model

Pre-IE8 (Removed in IE11). IE9 supports W3C events. Trident-based browsers (Maxthon) support this model as well.

  • attachEvent: Similar to W3C's addEventListener method.
  • detachEvent: Similar to W3C's removeEventListener method.
  • fireEvent: Similar to W3C's dispatchEvent method.
  • To prevent an event bubbling, developers must set the event's cancelBubble property.
  • To prevent the default action of the event to be called, developers must set the event's "returnValue" property.
  • The this keyword refers to the global window object.

Example of MS IE event model


Microsoft-specific model

Hey Joe!


var heyJoe = function () {
     window.alert("Hey Joe!");
}

// Add an event handler
document.attachEvent("onclick", heyJoe);

// Add another event handler
window.attachEvent("onload", heyJoe);

// Remove the event handler just added
window.detachEvent("onload", heyJoe);

Events in jQuery

.bind()

Attach a handler to an event for the elements.

.bind( eventType [, eventData ], handler(eventObject) )


$( "#foo" ).bind( "click", function() {
  alert( "User clicked on 'foo.'" );
});

//Multiple event types can be bound at once by including each one separated by a space:
$( "#foo" ).bind( "mouseenter mouseleave", function() {
  $( this ).toggleClass( "entered" );
});

Event object

The handler callback can take parameters


$( "#foo" ).bind( "click", function( event ) {
    alert( "The mouse cursor is at (" +
      event.pageX + ", " + event.pageY +
      ")" );
  });

Returning false from a handler is equivalent to calling both .preventDefault() and .stopPropagation() on the event object.

.live

Same as .bind, but works for elements created after the page has been loaded

DEPRECATED!

.unbind

Remove a previously-attached event handler from the elements.


//Removes the handlers regardless of type.
$( "#foo" ).unbind();

//Removing handlers for click event type
$( "#foo").unbind( "click" );

//Assuring that only the certain handler is removed
var handler = function() {
  alert( "The quick brown fox jumps over the lazy dog." );
};
$( "#foo" ).bind( "click", handler );
$( "#foo" ).unbind( "click", handler );

.die

Opposite to .live

DEPRECATED!

A proper way to attach an event handler


$( "p" ).on( "click", function() {
  alert( $( this ).text() );
})

//passing event handler by name
function notify() {
  alert( "clicked" );
}
$( "button" ).on( "click", notify );

//Passing data to the handler
function myHandler( event ) {
  alert( event.data.foo );
}
$( "p" ).on( "click", { foo: "bar" }, myHandler );
JSBin: http://jsbin.com/IsexoMi/1/edit

.one()

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

.off

Remove an event handler.


$( "p" ).off();

//Remove all delegated click handlers from all paragraphs:
$( "p" ).off( "click", "**" );

//Removing the certain handler
var foo = function() {
  // Code to handle some kind of event
};
 
// ... Now foo will be called when paragraphs are clicked ...
$( "body" ).on( "click", "p", foo );
 
// ... Foo will no longer be called.
$( "body" ).off( "click", "p", foo );
JSBin: http://jsbin.com/iBASEDix/1/edit

Form events

Shortcuts for for .on( "event", handler )


.blur( handler(eventObject) ) //JS on blur event
.change()
.focus()
.focusin()
.select()
.submit()

Form events


.click()
.dblclick()
.focusout()
.hover()
.mousedown()
.mouseenter()
.mouseleave()
.mousemove()
.mouseout()
.mouseover()
.mouseup()
 //Bind two or more handlers to the matched elements, 
 // to be executed on alternate clicks.
.toggle()

Keyboard events


.focusout()
.keydown()
.keypress()
.keyup()

Event object

jQuery’s event system normalizes the event object according to W3C standards. The event object is guaranteed to be passed to the event handler. Most properties from the original event are copied over and normalized to the new event object.

Proxy

Takes a function and returns a new one that will always have a particular context.

Animate

.fadeToggle()

Display or hide the matched elements by animating their opacity.


 
   
  
  
  

This paragraph has a slow, linear fade.

This paragraph has a fast animation.

 

$( "button:first" ).click(function() {
  $( "p:first" ).fadeToggle( "slow", "linear" );
});
$( "button:last" ).click(function() {
  $( "p:last" ).fadeToggle( "fast", function() {
    $( "#log" ).append( "
finished
" ); }); });
JSBin: http://jsbin.com/OSoVUkI/1/edit

.slideToggle()

Display or hide the matched elements with a sliding motion.

JSBin: http://jsbin.com/AqAkUrE/1/edit JSBin: http://jsbin.com/OliPiCUR/1/edit

.toggle()

Display or hide the matched elements.

 
//With no parameters simply toggles the visibility:
$( ".my_target" ).toggle();
//with callback
$( "#clickme" ).click(function() {
  $( "#book" ).toggle( "slow", function() {
    // Animation complete.
  });
});
//with Bool parameter
$( "#foo" ).toggle( showOrHide );
//equal to
if ( showOrHide === true ) {
  $( "#foo" ).show();
} else if ( showOrHide === false ) {
  $( "#foo" ).hide();
}

JSBin: http://jsbin.com/uXaHUjaB/1/edit

.animate()

Perform a custom animation of a set of CSS properties.

 
<div id="clickme">
  Levioso!
</div>
<img id="book" src="book.jpg" alt="" 
width="100" height="123"
  style="position: relative; left: 10px;">
 
$( "#clickme" ).click(function() {
  $( "#book" ).animate({
    opacity: 0.25,
    left: "+=50",
    height: "toggle"
  }, 5000, function() {
    // Animation complete.
  });
});

Step function

A callback function that is fired at each step of the animation.

 
$( "li" ).animate({
  opacity: .5,
  height: "50%"
}, {
  step: function( now, fx ) {
    var data = fx.elem.id + " " + fx.prop + ": " + now;
    $( "body" ).append( "
" + data + "
" ); } });

Called for each animated property of each animated element.

Progress function

A function to be called after each step of the animation, only once per animated element regardless of the number of animated properties.

Complete function

A callback function that is fired once animation is complete.

 
$( "#clickme" ).click(function() {
  $( "#book" ).animate({
    opacity: 0.25,
    left: "+=50",
    height: "toggle"
  }, 5000, function() {
    // Animation complete.
  });
});

Queue

queue: A Boolean indicating whether to place the animation in the effects queue. If false, the animation will begin immediately.

 
//without queue
$("#animate").click(function() {
    $("#content")
        .animate({"height": "100px"}, 500)
        .animate({"width": "250px"}, 500);
});

//with queue. Animations run at the same time.
$("#animate").click(function() {
    $("#content")
        .animate({"height": "100px"}, {"queue": false, "duration": 500})
        .animate({"width": "250px"}, 500);
});

When a custom queue name is used the animation does not automatically start; you must call .dequeue("queuename") to start it.

JSBin: http://jsbin.com/ETOJibep/1/edit

.stop()

Stop the currently-running animation on the matched elements.

 
$( "#go" ).click(function() {
  $( ".block" ).animate({ left: "+=100px" }, 2000 );
});
 
// Stop animation when button is clicked
$( "#stop" ).click(function() {
  $( ".block" ).stop();
});
 
// Start animation in the opposite direction
$( "#back" ).click(function() {
  $( ".block" ).animate({ left: "-=100px" }, 2000 );
});

Utility functions

jQuery.fx.off

Globally disable all animations.

When this property is set to true, all animation methods will immediately set elements to their final state when called, rather than displaying an effect. This may be desirable for a couple reasons:

  • jQuery is being used on a low-resource device.
  • Users are encountering accessibility problems with the animations (see the article Turn Off Animation for more information).

jQuery.support

A collection of properties that represent the presence of different browser features or bugs. Intended for jQuery's internal use

 
if (!$.support.leadingWhitespace) {
    //IE7 and 8 stuff
}

jQuery.noConflict()

Relinquish jQuery's control of the $ variable.

 
//if other script uses $
<script src="other_lib.js"></script>
<script src="jquery.js"></script>
<script>
$.noConflict();
jQuery( document ).ready(function( $ ) {
  // Code that uses jQuery's $ can follow here.
});
// Code that uses other library's $ can follow here.

//or two different jqueries

<script src="other_lib.js"></script>
<script src="jquery.js"></script>
<script>
$.noConflict();
// Code that uses other library's $ can follow here.
</script>

</script>
JSBin: http://jsbin.com/OCudoJi/1/edit

Goodies

 
.trim() //Remove the whitespace from the beginning and end of a string.

jQuery.map() //Translate all items in an array or object to new 
//array of items.

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

.each() //Iterate over a jQuery object, 
//executing a function for each matched element.

.grep() // Finds the elements of an array which satisfy a filter function. 
//The original array is not affected.

Array goodies

 
jQuery.inArray( "John", arr ) ); //Search for a specified value within 
//an array and return its index (or -1 if not found).

// Returns a NodeList
var elems = document.getElementsByTagName( "div" );
// Convert the NodeList to an Array
var arr = jQuery.makeArray( elems );

jQuery.unique() //Sorts an array of DOM elements, in place, with 
//the duplicates removed. ONLY works on arrays of DOM elements.

var newArray = $.merge([], oldArray); // Merge the contents of two 
//arrays together into the first array.

$.param({ a: { b: 1, c: 2 }, d: [ 3, 4, { e: 5 } ] });
// "a[b]=1&a[c]=2&d[]=3&d[]=4&d[2][e]=5"
//serialize


Extend

Merge the contents of two or more objects together into the first object.

 
var object1 = {
  apple: 0,
  banana: { weight: 52, price: 100 },
  cherry: 97
};
var object2 = {
  banana: { price: 200 },
  durian: 100
};
 
// Merge object2 into object1
$.extend( object1, object2 );
//{"apple":0,"banana":{"price":200},"cherry":97,"durian":100}

Even more goodies

 
$.isArray([]) //checks if something is an array

//Check an object to see if it's empty.
jQuery.isEmptyObject({}); // true
jQuery.isEmptyObject({ foo: "bar" }); // false

//Finds out if the parameter is a function.
$.isFunction(function() {}); //true

//Check to see if an object is a plain object 
//(created using "{}" or "new Object").
jQuery.isPlainObject({}) // true
jQuery.isPlainObject( "test" ) // false

//Check to see if a DOM node is within an XML document 
//(or is an XML document).
jQuery.isXMLDoc( document ) // false

..Even more goodies

 

//You can use this empty function when you wish to pass 
//around a function that will do nothing.
jQuery.noop() 

//Check to see if a DOM element is a descendant of another DOM element.
$.contains( document.documentElement, document.body ); // true
$.contains( document.body, document.documentElement ); // false

//Takes a well-formed JSON string and returns the 
//resulting JavaScript object.
var obj = jQuery.parseJSON( '{ "name": "John" }' );

//Execute some JS code globally
function test() {
  jQuery.globalEval( "var newVar = true;" )
}
test();
// newVar === true

jQuery.getScript()

Load a JavaScript file from the server using a GET HTTP request, then execute it.

 

var url = "https://raw.github.com/jquery/jquery-color/master/jquery.color.js";
$.getScript( url, function() {
  $( "#go" ).click(function() {
    $( ".block" )
      .animate({
        backgroundColor: "rgb(255, 180, 180)"
      }, 1000 )
      .delay( 500 )
      .animate({
        backgroundColor: "olive"
      }, 1000 )
      .delay( 500 )
      .animate({
        backgroundColor: "#00f"
      }, 1000 );
  });
});

jQuery plugin

A brand new way to alert('Hello World!')

Useful links

AJAX

What is AJAX?

AJAX = Asynchronous JavaScript and XML.

AJAX is the art of exchanging data with a server, and updating parts of a web page - without reloading the whole page.

.load()

Load data from the server and place the returned HTML into the matched element.

 
//with callback
$( "#result" ).load( "ajax/test.html", function() {
  alert( "Load was performed." );
});

//Only fetch part of document
$( "#result" ).load( "ajax/test.html #container" );

.get()

Load data from the server using a HTTP GET request.

 
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.get( "example.php", {foo: bar}, function() {
  alert( "success" );
})
  .done(function() {
    alert( "second success" );
  })
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "finished" );
  });
 
// Perform other work here ...
 
// Set another completion function for the request above
jqxhr.always(function() {
  alert( "second finished" );
});

.getJSON()

Load JSON-encoded data from the server using a GET HTTP request.

 
$.getJSON( "test.js", { name: "John", time: "2pm" } )
  .done(function( json ) {
    console.log( "JSON Data: " + json.users[ 3 ].name );
  })
  .fail(function( jqxhr, textStatus, error ) {
    var err = textStatus + ", " + error;
    console.log( "Request Failed: " + err );
});

.post()

Load data from the server using a HTTP POST request.

 
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.post( "example.php", {foo: bar}, function() {
  alert( "success" );
})
  .done(function() {
    alert( "second success" );
  })
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "finished" );
});
 
// Perform other work here ...
 
// Set another completion function for the request above
jqxhr.always(function() {
  alert( "second finished" );
});

.ajax()

Perform an asynchronous HTTP (Ajax) request.

The long version

 
//TL DR
$.ajax({
  type: "POST",
  url: "some.php",
  data: { name: "John", location: "Boston" }
})
  .done(function( msg ) {
    alert( "Data Saved: " + msg );
  });

$.ajax({
  url: "test.html",
  cache: false
})
  .done(function( html ) {
    $( "#results" ).append( html );
  });

.ajaxSetup()

Set default values for future Ajax requests. Its use is not recommended.


//Sets the defaults for Ajax requests to the 
//url "/xmlhttp/", disables global handlers and 
//uses POST instead of GET. The following Ajax requests 
//then sends some data without having to set anything else. 
$.ajaxSetup({
  url: "/xmlhttp/",
  global: false,
  type: "POST"
});
$.ajax({ data: myData });

jQuery UI

http://jqueryui.com/ - cancer, but sometimes you gotta do, what you’ve got to do.

jQuery mobile

jQuery Mobile: Touch-Optimized Web Framework for Smartphones & Tablets

When not to use jQuery

  • jquerymobile analog- http://eightmedia.github.io/hammer.js/
  • http://tech.pro/tutorial/1385/out-growing-jquery
  • http://remysharp.com/2013/04/19/i-know-jquery-now-what/
  • http://www.leebrimelow.com/native-methods-jquery/
  • http://www.2ality.com/2013/06/triggering-events.html
  • https://github.com/eligrey/classList.js/blob/master/classList.js
  • http://blog.ponyfoo.com/2013/06/10/uncovering-the-native-dom-api
  • http://zeptojs.com/

Reading

The End