OSCON jQuery Training. ‣The jQuery Project. ‣Including jQuery. ‣The jQuery
Object. ‣Introduction to JavaScript. ‣Lifecycle of a Page. Introduction to jQuery ...
THE jOUERY COMPANY
http://appendto.com
Copyright © 2010 appendTo, LLC.
OSCON jQuery Training
Introduction to jQuery
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Introduction to jQuery ‣ The jQuery Project ‣ Including jQuery ‣ The jQuery Object ‣ Introduction to JavaScript ‣ Lifecycle of a Page
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
The jQuery Project
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
jQuery Project - jquery.org (Software Freedom Conservancy)
jQuery Core
jQuery UI
jquery.com
jqueryUI.com
Sizzle JS
QUnit
sizzlejs.com
qunitjs.com
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
‣ jquery.com
Downloading
‣ api.jquery.com
Documentation
‣ forum.jquery.com
Community
‣ meetups.jquery.com ‣ plugins.jquery.com ‣ jqueryui.com
Local Community Extending
Project Supported UI Library
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Including jQuery
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Locations ‣ http://code.jquery.com/jquery-1.4.2.min.js ‣ SSL vs. Non SSL? ‣ src=“//code.jquery.com/jquery-1.4.2.min.js”
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Source
Minified Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
The jQuery Object function jQuery(selector) { ... } // Select an element with jQuery jQuery(‘body’); // Use the $ for brevity var $ = jQuery; $(‘body’);
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Introduction to JavaScript
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Introduction to JavaScript ‣ Script blocks ‣ Quotes and Whitespace ‣ Variables ‣ Functions ‣ Object-Hash ‣ Objects
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Script Blocks ‣ Scripts can be included inline ‣ // Your script here
‣ Or externally ‣
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Quotes & Whitespace // Single Quotes var name = ‘John’; // Double Quotes var name = “John”; // Whitespace var name
=
‘John’;
// Terminate statements with a semi colon; // Will work, but bad practice! var name = ‘John’ Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Variables ‣ Variable names may include a-zA-Z0-9_$ as valid characters ‣ Variable scope is applied through the use of the var keyword ‣ Variables have type: ‣ object, number, string, boolean ‣ array(object), function(object)
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Variables // String var name = ‘John’; // Integer(number) var age = 30; // Array var children = [‘Jane’, ‘Jimmy’]; // Boolean var isMarried = true;
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Functions function alertName() { alert(‘Hello John’); } // Accept arguments function alertName(name) { alert(‘Hello ‘ + name); } // Call the function alertName(‘John’); //Hello John
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Functions // Function assignment var alertName = function(name) { alert(‘Hello ‘ + name); } // Call the function alertName(‘John’); //Hello John
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Variable Scope var name = ‘John’; function myFunction() { alert(‘Name is: ‘ + name); } ... myFunction(); //Name is John
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Variable Scope var name = ‘John’; function myFunction() { var name = ‘Jim’; alert(‘Name is: ‘ + name); }
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Object-hash (Object Literal) // Empty object var person = {}; // Object-hash may contain key/values var person = { name: ‘John’, age: 30, children: [‘Jane’, ‘Jimmy’], isMarried: true };
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Object var person = { name: ‘John’, age: 30, introduceYourself: function() { alert(this.name + ‘ is ‘ + this.age); } }; person.introduceYourself();
//John is 30
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Lifecycle of a Page
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Lifecycle of a Page ‣ Initial HTTP Request ‣ Load Scripts, Stylesheets and Images ‣ Scripts block! ‣ Head first style, scripts later
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Page Load $(‘p’).css(‘color’, ‘red’); //magic
Hello world!
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
DOM Ready // Callback function function domIsReady() { $(‘body’).append(‘Hello world’); //magic } $(document).ready(domIsReady);
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Page Load function domIsReady() { $(‘p’).css(‘color’, ‘red’); //magic } $(document).ready(domIsReady);
Hello world!
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Page Load
Hello world!
$(‘p’).css(‘color’, ‘red’); //magic
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Questions?
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
jQuery and Selectors
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
jQuery and Selectors ‣ Selectors ‣ Compound Selectors ‣ Selecting by the API ‣ The Context Argument
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Selectors // Select By ID
$(‘#foo’);
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Selectors // Select by class
$(‘.myClass’)
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Selectors // Select by tag
$(“li”);
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Compound Selectors
$(‘p.important,p.warning’);
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Compound Selectors ‣ As of 1.4+ elements are always returned in document order
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Select By Relationship
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Select By Relationship // Children by method
$(“ul”).children();
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Select By Relationship // Children by selector
$(“ul > li”);
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Select By Relationship // Siblings by method
$(‘a’).siblings(); Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Select By Relationship // Siblings by method
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Select By Relationship // Parent by method
$(‘a’).parent(); Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Select By Relationship // Parent result
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Select By Relationship // Descendant by method
$(“ul”).find(‘a’);
//selector within find method
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Select By Relationship // Descendant by selector
$(“ul a”);
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Selector Pitfalls //Over selection $(‘div#myId’); vs. $(‘#myId’); //Under selection $(‘.randomClass’); vs. $(‘div.randomClass’);
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
The Context //Entire Document $(‘div’) //Scope your selector //$(‘selector’, ) $(‘#table’).find(‘selector’) $(‘a’).click(function() { $(‘span’, this)... });
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
The Context ‣ Two different scoping methods ‣ $(‘selector’, this) ‣ $(this).find(‘selector’) ‣ Can access context with the context property ‣ 1.3 and later
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Context Pitfalls var $mySelection = $(‘selector’, ‘#myid’); var $mySelection.context = ? var $mySelection2 = $(‘selector’, $(‘#myid’)[0]); var $mySelection2.context = ?
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Questions?
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
jQuery and Methods
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
jQuery and Methods ‣ Do Something ‣ Showing and Hiding ‣ Iteration ‣ Styling ‣ Behavior
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Do Something $('p').bind('click',function(){ $(this).effect('drop'); }); // hides element by pulling it left
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Do Something
One
Two
Three
// Find Something $(‘p’) // Do Something $(‘p’).hide(); // Generic Syntax $(‘p’) . ( [PARAMETERS] );
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Showing and Hiding
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Showing and Hiding // HTML
One
Two
Three
// Show the elements $(‘p’).show(); // Hide the elements $(‘p’).hide();
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Showing and Hiding // HTML
One
Two
Three
// Show the elements $(‘p’).show(); // Hide the elements $(‘p’).hide();
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Showing and Hiding // HTML
One
Two
Three
// Show the elements $(‘p’).show(); // Hide the elements $(‘p’).hide();
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Iteration
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Iteration
One
Two
Three
$(‘p’).each(function() { // Operates on each p individually var rand; rand = Math.floor( Math.random() * 1 ); if(rand > 1) { $(this).hide(); } }); Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Iteration
One
Two
Three
$(‘p’).each(function() { // Operates on each p individually var rand; rand = Math.floor( Math.random() * 1 ); if(rand > 1) { $(this).hide(); } }); Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Iteration
One
Two
Three
$(‘p’).each(function() { // Operates on each p individually var rand; rand = Math.floor( Math.random() * 1 ); if(rand > 1) { $(this).hide(); } }); Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Iteration
One
Two
Three
$(‘p’).each(function() { // Operates on each p individually var rand; rand = Math.floor( Math.random() * 1 ); if(rand > 1) { $(this).hide(); } }); Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Iteration ‣ The anonymous function
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
The Anonymous Function function foo() { ... }
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
The Anonymous Function function foo() { ... } var foo = function() { ... } //do this $(document).click(foo); //dont do this $(document).click(foo());
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
The Anonymous Function function foo() { ... } var foo = function() { ... } $(document).click(foo); $(document).click(function() { ... });
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Iteration // HTML
One
Two
Three
// Changes all elements returned // via Implicit Iteration $(‘p’).css(‘color’,‘red’);
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
“Each”itis AntiPattern // HTML
One
Two
Three
// Changes all elements returned // via incredibly inefficient explicit iteration $(‘p’).each(function(i,v){ $(this).css(‘color’,‘red’); });
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Styling
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Styling // HTML
One
Two
Three
$(‘p’).addClass(‘enabled’); $(‘p’).removeClass(‘foo’); $(‘p’).toggleClass(‘foo’);
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Styling //
Three
$(‘p’).addClass(‘enabled’); $(‘p’).removeClass(‘foo’); $(‘p’).toggleClass(‘foo’);
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Styling //
Three
$(‘p’).addClass(‘enabled’); $(‘p’).removeClass(‘foo’); $(‘p’).toggleClass(‘foo’);
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Styling //
Three
$(‘p’).addClass(‘enabled’); $(‘p’).removeClass(‘foo’); $(‘p’).toggleClass(‘foo’);
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Styling
One
Two
Three
$(‘p’).css(‘color’,‘red’); $(‘p’).css(‘font-weight’,‘bold’); $(‘p’).css({ color: ‘red’, fontWeight: ‘bold’ }); Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Styling
One
Two
Three
$(‘p’).css(‘color’,‘red’); $(‘p’).css(‘font-weight’,‘bold’); $(‘p’).css({ ‘background-color’: ‘blue’, fontWeight: ‘bold’, border: ‘1px solid black’ }); Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Behavior
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Behavior // HTML
One
Two
Three
$(‘p’).click(function(event) { $(this).css(‘color’, ‘red’); });
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Behavior // HTML
One
Two
Three
$(‘p’).hover(function(event) { $(this).css(‘color’, ‘red’); }, function(event) { $(this).css(‘color’, ‘’); });
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Behavior // HTML
One
Two
Three
// Add event $(‘p’).click(function(event) { $(this).css(‘color’, ‘red’); }); // Remove event $(‘p’).unbind(‘click’); Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Questions?
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Chaining and Sentences
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Chaining and Sentences ‣ Method Chaining ‣ The Stack Architecture ‣ Finding vs. Filtering Elements
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Method Chaining
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Method Chaining $(‘#myForm a’) .addClass(‘.highlight’) .click(function(){...}) .hover(function(){...},function(){...});
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Method Chaining $(‘#myForm a’) .addClass(‘.highlight’) .click(function(){...}) .hover(function(){...},function(){...});
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Method Chaining $(‘#myForm a’) .addClass(‘.highlight’) .click(function(){...}) .hover(function(){...},function(){...});
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Method Chaining $(‘#myForm a’) .addClass(‘.highlight’) .click(function(){...}) .hover(function(){...},function(){...});
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
What Breaks the Chain? //Getters vs. Setters $(...) //jQuery selector .html(‘Hello world’) .addClass(‘hello’) $(...) .html() .addClass(‘hello’)
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
What Breaks the Chain? //Getters vs. Setters $(...) .html(‘Hello world’) //non breaking .addClass(‘hello’) $(...) .html() .addClass(‘hello’)
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
What Breaks the Chain? //Getters vs. Setters $(...) .html(‘Hello world’) .addClass(‘hello’) //class will be added $(...) .html() .addClass(‘hello’)
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
What Breaks the Chain? //Getters vs. Setters $(...) .html(‘Hello world’) .addClass(‘hello’) $(...) //jQuery selector .html() .addClass(‘hello’)
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
What Breaks the Chain? //Getters vs. Setters $(...) .html(‘Hello world’) .addClass(‘hello’) $(...) .html() //breaking .addClass(‘hello’)
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
What Breaks the Chain? //Getters vs. Setters $(...) .html(‘Hello world’) .addClass(‘hello’) $(...) .html() .addClass(‘hello’) //runtime error
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
What Breaks the Chain? //put getter last var myHtml = $(...) .addClass(‘hello’) .html(); //store selection in variable //when multiple getters //are needed var $mySelection = $(...); var myHtml = $mySelection.html();
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
The Stack Architecture
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
jQuery Collections $(‘body’)
(Buckets)
[body]
.find(‘p’) .find(‘a’)
[p, p, p] => [body] [a, a] => [p, p, p] => [body]
.addClass(‘foo’) .end() .end()
[p, p, p] => [body] [body]
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Method Chaining $(‘tr’) .filter(‘:odd’) .addClass(‘odd’) .end() .find(‘td.company’) .addClass(‘companyName’);
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Finding vs. Filtering
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Finding Elements $(‘body’)
[body]
.find(‘p’) .find(‘a’)
[p, p, p] => [body] [a, a] => [p, p, p] => [body]
.addClass(‘foo’) .end() .end()
[p, p, p] => [body] [body]
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Filtering Elements $(‘a’)
[a, a.foo, a]
.filter(‘.foo’)
[a.foo] => [a, a.foo, a]
.attr(‘href’, ‘http://appendto.com’) .end()
[a, a.foo, a]
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Find vs. Filter ‣ find() searches the DOM for descendants of elements in the current jQuery wrapped collection
‣ filter() searches the current jQuery collection and returns a reduced set (sub set)
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Questions?
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
jQuery and DOM Manipulation
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
jQuery and DOM Manipulation ‣ Creating Elements ‣ Inserting Elements ‣ Removing Elements ‣ Cloning Elements ‣ Wrapping Elements ‣ Attributes ‣ Data
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Creating Elements
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Creating Elements $(‘
’); // Creates ...
var ul = $(‘
’); // Creates ...
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Creating Elements // New in 1.4 $("
", { class: "test", text: "Click me!", click: function(){ $(this).toggleClass("test"); } }); // Clicking toggles the class
Click me!
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Inserting Elements
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Inserting Elements // Before
Apple
Orange
$(‘p’).after(‘
’); // After
Apple
Orange
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Inserting Elements // Before
Apple
Orange
$(‘p’).before(‘
’); // After
Apple
Orange
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Inserting Elements // Before
Apple
Orange
$(‘#apple’).prepend(‘
’); $(‘#orange’).append(‘
’); // After
Apple
Orange
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
// Before
Apple
Orange
$(‘
’).prependTo(‘#apple’); $(‘
’).appendTo(‘#orange’); // After
Apple
Orange
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Element Creation Best Practice //Use object literal syntax for single (non-nested) element creation //If creating nested elements use a single string //yes $(‘
’) .appendTo(‘body’); //slower $(‘
link text’) .appendTo(‘
’) .appendTo(‘body’); Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Removing Elements
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Removing Elements // Before
// Removing Elements Directly $(‘p’).remove(); // After
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Empty Elements // Before
$(‘p’).empty(); // After
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Detaching Elements // Before
var $bucket = $(‘p’).detach(); $bucket.insertAfter(‘#container’); // After
Foo Bar
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Cloning Elements
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Cloning Elements // Before
The Source
// Copies the element instead of moving it $(‘#source’).clone().appendTo(‘body’); // After
The Source
The Source
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Cloning Elements // Before
The Source
// Copies the element instead of moving it $(‘#source’).clone(true).appendTo(‘body’); // After
The Source
The Source
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Modifying Elements
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Wrapping Elements // Before
Hello world
Foo bar
$(‘p’).wrap(‘
’);
// After
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Wrapping Elements // Before
Hello world
Foo bar
// As a group $(‘p’).wrapAll(‘
’); // After
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Wrapping Elements // Before
Hello world
Foo bar
// Wrapping Children $(‘p’).wrapInner(‘
’); // After
Hello world
Foo bar
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Unwrapping Elements
(new in 1.4+)
// Before
//Individually $(‘p’).unwrap(); // After
Hello world
Foo bar
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Attributes
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
.attr() // Before
$(‘#logo’).attr(‘src’, ‘logo.png’); // After
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
.attr() // Markup
var title = $(‘#logo’).attr(‘title’); //title === “Hello world”
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
.attr() // Before
$(‘#logo’).attr({ src: ‘logo.png’, alt: ‘Company logo’ }); // After
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
.attr() // Before
$(‘#logo’).attr(‘class’, function() { var c = [‘a’, ‘b’, ‘c’]; var r = Math.floor( Math.random() * 3 ); return c[r]; }); // After (randomized class name)
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Element Contents // Returns ‘
HEADER var theHtml = $(‘#header’).html(); $(‘#header’).html(‘
’); Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Element Contents // Returns ‘HEADER’ $(‘#header’).text(); $(‘#header’).text(‘
Hello world’); Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
.val() // Returns ‘foo bar’ $(‘#email’).val(); // Sets value to ‘The value’ $(‘#email’).val(‘The value’); $(‘select’).val([ ‘red’, ‘green’ ]);
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Data
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Data // HTML
// Potential for a Memory Leak var elem = $(‘#myDiv’)[0]; elem.foo = new String(‘xyz’);
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Data // HTML
// Cross Browser Safe Method to attach data $(‘#myDiv’).data(‘foo’, new String(‘xyz’)); var myVar = $(‘#myDiv’).data(‘foo’); $(‘#myDiv’).removeData(‘foo’);
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Data
(new in 1.4+)
var object1 = { abc: 123 }; var object2 = { xyz: 789 }; $(‘#myDiv’).data(‘object1’, object1); $(‘#myDiv’).data(‘object2’, object2); var objects = $(‘#myDiv’).data(); objects.object1; objects.object2;
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Questions?
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
jQuery and Events
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
jQuery and Events ‣ Binding Events ‣ Binding Multiple Events ‣ The Event Object ‣ Event Namespacing ‣ Event Propagation
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Binding Events
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
jQuery Event Shortcuts // Binding an event $('a.tab').click(function(){ // event handling code $(this).css(‘color’, ‘red’); }); // Binding an event $('a.tab').mouseover(function(){ // event handling code $(this).css(‘color’, ‘red’); });
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Common Types of Events ‣ click, dblclick, mouseover, mouseout ‣ mouseenter, mouseleave ‣ change, focus, blur ‣ keydown, keyup, keypress ‣ scroll, resize
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Hover Shortcut // mouseenter, mouseleave $(‘li’).hover( function() { $(this).addClass(‘hover’); }, function() { $(this).removeClass(‘hover’); });
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Hover Shortcut // mouseenter, mouseleave $(‘li’) .bind(‘mouseenter’, function() { $(this).addClass(‘hover’); }) .bind(‘mouseleave’, function() { $(this).removeClass(‘hover’); });
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Hover Shortcut // Optimal hover $(‘li’) .hover(function(evt) { var add = evt.type == ‘mouseenter’; $(this).toggleClass(‘hover’, add); });
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Hover Shortcut // Optimal hover $(‘li’) .hover(function(evt) { $(this).toggleClass(‘hover’, evt.type == ‘mouseenter’); }); $(‘li’) .bind(‘mouseenter mouseleave’,fn);
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Binding Events with .bind() // Binding an event $('a.tab').bind('click',function(e){ // event handling code $(this).css(‘color’, ‘red’); }); // Unbinding an event $('a.tab').unbind('click');
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Binding Events // Bind an event to execute once $('a.tab').one('click',function(e){ // event handling code $(this).css(‘color’,‘red’); });
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Binding Multiple Events
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Binding Multiple Events $(‘div’).bind(‘mouseover mouseout’, function(e) { if ( e.type == ‘mouseover’ ) { $(this).addClass('highlight'); } elseif ( e.type == ‘mouseout’ ) { $(this).removeClass('highlight'); } }); $(‘div’).unbind(‘mouseover mouseout’); $(‘div’).unbind(); Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Binding Multiple Events $('a.tab').hover( function(e){ $(this).addClass('highlight'); }, function(e){ $(this).removeClass('highlight'); } ); // Unbind the hover event $(‘a.tab’).unbind('mouseenter mouseleave')
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Binding Multiple Events // Arbitrary number of functions to execute cyclically on click $('a.tab').toggle( function(){ $(this).css('color','red'); }, function(){ $(this).css('color','yellow'); }, function(){ $(this).css('color','green'); }); Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
The Event Object
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
The Event Object ‣ Event Object Properties
type timeStamp
pageX pageY
target relatedTarget currentTarget
data result which
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
The Event Object ‣ event.type
The name of the event (all lowercase)
‣ event.target
The element that the event originated at
‣ event.pageX, event.pageY
Coordinates in pixels of mouse position on page (not populated for key events)
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Event Namespacing
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Event Namespacing ‣ Tagging for event handlers ‣ Added in jQuery 1.2
namespace post - http://bit.ly/aCaFXS
‣ Simplifies unbinding of events
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Binding Namespaced Events $(‘div’) .bind(‘click’, fn) .bind(‘click.foo’, fn) .bind(‘mouseover.foo’, fn); // Unbind click.foo event $(‘div’).unbind(‘click.foo’); // Unbind all .foo namespaced events // click.foo, mouseover.foo $(‘div’).unbind(‘.foo’);
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Event Propagation
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Event Propagation - Anchor Tag
$(‘div’).click(function() { alert(‘clicked div!’); }); $(‘a’).click(function() { alert(‘clicked!’); });
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Event Propagation - Paragraph Tag
$(‘div’).click(function() { alert(‘clicked div!’); }); $(‘a’).click(function() { alert(‘clicked!’); });
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Event Propagation - Paragraph Tag
$(‘div’).click(function(evt) { // evt.target == a alert(‘clicked div!’); }); $(‘a’).click(function() { alert(‘clicked!’); }); Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Event Propagation - Div Tag
$(‘#navigation’).click(function(evt) { // evt.target == anchor tag alert(‘clicked div!’); // this = Reference to div DOM element $(this).addClass(‘active’); }); $(‘a’).click(function() {
alert(‘clicked!’);
});
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Event Propagation - Stopping Prop.
$(‘div’).click(function() { alert(‘clicked div!’); }); $(‘a’).click(function() { alert(‘clicked!’); return false; }); Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Event Propagation - Stopping Prop.
$(‘div’).click(function() { alert(‘clicked div!’); }); $(‘a’).click(function(evt) { alert(‘clicked!’); evt.stopPropagation(); evt.preventDefault(); return false; // Same as two lines above }); Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Event Propagation - Returning False Stop events from bubbling Prevent the default event action from occurring
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Live Events
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Live Events - Binding // Before
One
// Code $(‘p’).live(‘click’,function() { alert(‘P Pressed’) }); $(‘
’).text(‘Two’).appendTo(‘body’); // After
One
Two
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Live Events - Unbinding // Remove with .die() $(‘p’).die(); // .die() also accepts an event type $(‘p’).die(‘click’); // Namespace Example $(‘p’).die(‘click.one’);
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Live Events - Namespacing // .live() performs just like .bind() $(‘p’).live(‘click dblclick’, function(e){ if(e.type == ‘click’) { ... } }); // .live() can take namespaced events $(‘p’).live(‘click.one’,function(e) { alert(‘Click.one’); });
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Live and delegate //1.4+ - live events can be given a context $("table").each(function(){ $("td", this).live("hover", function(){ $(this).toggleClass("hover"); }); }); //delegate is short hand method for this best //practice pattern $("table").delegate("td", "hover", function(){ $(this).toggleClass("hover"); }); Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Triggering Events // HTML
One
// Assign the event $(‘p’).live(‘click’,function() { alert(‘P Pressed’) }); // Trigger the event manually $(‘p’).trigger(‘click’);
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Triggering Events // HTML
One
// Assign the event $(‘p’).live(‘click’,function() { alert(‘P Pressed’) }); // Some Event types have shortcuts $(‘p’).click();
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Event Parameters
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Event Data - Event Object // HTML
One
// Define the custom event var foo = ‘bar’; $(‘p’).bind(‘click’, {msg: foo}, function(evt){ alert(‘Parameter: ’+ evt.data.msg) } );
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Questions?
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
jQuery and Ajax Lesson 7
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
jQuery and Ajax ‣ Request Types ‣ Data Formats ‣ Request Callbacks ‣ Making a Request
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Request Types
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Request Types Core Method
Shortcuts
‣ $.ajax();
‣ $.get(); ‣ $.post(); ‣ $.getJSON(); ‣ $.getScript(); ‣ $( ... ).load();
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Data Formats
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Data Formats ‣ xml
Returned as DOM
‣ html
Returned as String
‣ json
Returned as Object
‣ jsonp ‣ text
Returned as Object
Returned as String
‣ script
Evaluated & Returned as String
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Request Callbacks
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Request Callbacks ‣ success: function(data, status, XMLHttpRequest) { ... } ‣ error: function(XMLHttpRequest, textStatus, error) { ... } ‣ complete: function(XMLHttpRequest, status) { ... }
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Making a Request
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Making a Request $.get(‘page.php’, function(data) { $(data).appendTo(‘body’); }, ‘html’); var data = { fname: ‘Andrew’, lname: ‘Wirick’ }; $.post(‘page.php’, data, function(data) { $(data).appendTo(‘body’); }, ‘html’);
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Making a Request JSON // Response {“names”: [“Jonathan”, “Mike”, “Andrew”], “states”: {“NE” : “Nebraska”}, “year” : “2010” }
$.getJSON(‘page.php’, function(json) { $(‘body’).append( json.names[0] ); $(‘body’).append( json.states.NE ); });
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Making a Request JSON // Response { “names”: [“Jonathan”, “Mike”, “Andrew”] }
$.getJSON(‘page.php’, function(json) { $.each(json.names, function(i, val) { $(‘body’).append( val ); }); });
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Making a Request XML // Response Back to the future $.get(‘movies.php’, function(xml) { var title = $(xml) .find(‘movie[id=123] > title’) .text(); $(‘body’).append( title ); }, ‘xml’);
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Making a Request XML // Response Some data ]]> $.get(‘movies.php’, function(root) { var title = $(root) .find(‘document’) .text(); $(‘body’).append( title ); }, ‘xml’);
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Cross Domain Requests var url = ‘http://flickr.com...’; $.getJSON(url, function(json) { // Iterate the items and generate HTML });
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Questions?
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY
OSCON jQuery Training
Thank you for coming! http://appendTo.com @appendTo
Copyright © 2010 appendTo, LLC. THE jOUERY COMPANY