Slide 1

Slide 1 text

1

Slide 2

Slide 2 text

2 $(‘knowledge’).appendTo(‘you’);

Slide 3

Slide 3 text

3 What is jQuery? Why should I use it? Teach me how to use the API.

Slide 4

Slide 4 text

Introduction What is jQuery?

Slide 5

Slide 5 text

5 It’s basically JavaScript made more accessible.

Slide 6

Slide 6 text

Well.. With JavaScript, cross-browser Ajax looks like: 6 function  sendRequest(url,callback,postData)  {        var  req  =  createXMLHTTPObject();        if  (!req)  return;        var  method  =  (postData)  ?  "POST"  :  "GET";        req.open(method,url,true);        req.setRequestHeader('User-­‐Agent','XMLHTTP/1.0');        if  (postData)                req.setRequestHeader('Content-­‐type','application/x-­‐www-­‐form-­‐urlencoded');        req.onreadystatechange  =  function  ()  {                if  (req.readyState  !=  4)  return;                if  (req.status  !=  200  &&  req.status  !=  304)  {                        return;                }                callback(req);        }        if  (req.readyState  ==  4)  return;        req.send(postData); } var  XMLHttpFactories  =  [        function  ()  {return  new  XMLHttpRequest()},        function  ()  {return  new  ActiveXObject("Msxml2.XMLHTTP")},        function  ()  {return  new  ActiveXObject("Msxml3.XMLHTTP")},        function  ()  {return  new  ActiveXObject("Microsoft.XMLHTTP")} ]; function  createXMLHTTPObject()  {        var  xmlhttp  =  false;        for  (var  i=0;i

Slide 7

Slide 7 text

Well.. With JavaScript, cross-browser Ajax looks like: 7 function  sendRequest(url,callback,postData)  {        var  req  =  createXMLHTTPObject();        if  (!req)  return;        var  method  =  (postData)  ?  "POST"  :  "GET";        req.open(method,url,true);        req.setRequestHeader('User-­‐Agent','XMLHTTP/1.0');        if  (postData)                req.setRequestHeader('Content-­‐type','application/x-­‐www-­‐form-­‐urlencoded');        req.onreadystatechange  =  function  ()  {                if  (req.readyState  !=  4)  return;                if  (req.status  !=  200  &&  req.status  !=  304)  {                        return;                }                callback(req);        }        if  (req.readyState  ==  4)  return;        req.send(postData); } var  XMLHttpFactories  =  [        function  ()  {return  new  XMLHttpRequest()},        function  ()  {return  new  ActiveXObject("Msxml2.XMLHTTP")},        function  ()  {return  new  ActiveXObject("Msxml3.XMLHTTP")},        function  ()  {return  new  ActiveXObject("Microsoft.XMLHTTP")} ]; function  createXMLHTTPObject()  {        var  xmlhttp  =  false;        for  (var  i=0;i

Slide 8

Slide 8 text

Well.. But with jQuery, it’s as simple as this: 8 // Get the latest attendees $.get("/attendees.jsp", data: { range: 'latest'}, function( html) { $("#results").append( html ); } });

Slide 9

Slide 9 text

Well.. With JavaScript, you would style elements like this.. 9 var elems = document.getElementsByClassName('attendee'), len = elems.length, i=0; for(; i

Slide 10

Slide 10 text

Well.. With JavaScript, you would style elements like this.. 10 var elems = document.getElementsByClassName('attendee'), len = elems.length, i=0; for(; i

Slide 11

Slide 11 text

Well.. With jQuery, it’s just a simple one-liner: 11 $('.attendee').css('backgroundColor','orange'); before a2er

Slide 12

Slide 12 text

12 It’s lightweight (31kb)

Slide 13

Slide 13 text

13 Extensively tested *QUnit  unit  tests  exist  for  the  enAre  API

Slide 14

Slide 14 text

14 Let’s you write less and do more

Slide 15

Slide 15 text

15 “What does that mean?”

Slide 16

Slide 16 text

16 jQuery allows you to easily select elements on a page and manipulate or add some new behaviour to them.

Slide 17

Slide 17 text

jQuery.. –Simplifies traversing the DOM –Powerful selection engine –Eases element styling through JavaScript –Powerful methods for element animation –Cross-browser Ajax interactions –DOM data-storage –and more! 17

Slide 18

Slide 18 text

jQuery.. Normalises many cross-browser quirks so don’t have to worry about them 18

Slide 19

Slide 19 text

Helps minimize issues with this bastard: 19 Hi! I’m IE6

Slide 20

Slide 20 text

jQuery.. –It’s open-source –Great for beginners wishing to ‘break’ into front-end web development –Developers from any other language background can start using it easily 20

Slide 21

Slide 21 text

21 “Why should I use it?”

Slide 22

Slide 22 text

Reasons like this.. 22

Slide 23

Slide 23 text

and maybe this.. 23

Slide 24

Slide 24 text

But mostly.. –jQuery is extensively documented –Large online community here to help • Forums • Blogs • Tutorials • Twitter • IRC (#jquery on freenode) • Conferences • Books 24

Slide 25

Slide 25 text

Who uses jQuery? 25

Slide 26

Slide 26 text

Usage: Top 10K Sites 26 Over 50% Using jQuery

Slide 27

Slide 27 text

Usage: Top 1 Million Sites 27 Over 60% Using jQuery

Slide 28

Slide 28 text

Where Are We Now? Project status

Slide 29

Slide 29 text

Some history –jQuery was first released in January, 2006. –Initially developed by John Resig 29

Slide 30

Slide 30 text

Some history –We’ve gone through several versions since then • 1.2.* • 1.3.* • 1.4.* • 1.5.* • 1.6.* –Project now supported by: • 30+ Open-source contributors • Multiple sub-teams 30

Slide 31

Slide 31 text

Status • We’ve just released jQuery 1.7.1 31

Slide 32

Slide 32 text

Status • Lots of new changes: –$.Callbacks –Better Events API • .on() • .off() –Performance optimisations • A little of the API has been deprecated • Looking to clean-up ‘cruft’ by 1.8 32

Slide 33

Slide 33 text

Status • This is one of the first presentations to incorporate these changes • Useful to keep in mind if reading jQuery books as some of these are already out of date • You’ll get an up-to-date run-through today! 33

Slide 34

Slide 34 text

Getting setup Let’s get jQuery on your page

Slide 35

Slide 35 text

35 ‘How do I start using this thing?’

Slide 36

Slide 36 text

Setup • Head over to jQuery.com: 36 Click  download

Slide 37

Slide 37 text

Setup • Create a new HTML file • Include jQuery using a tag 37 <!DOCTYPE html> <html> <head> <script src="jquery-1.7.min.js"> jQuery test

Slide 38

Slide 38 text

Alternatively • Load it from the Google CDN • This can be faster than self-hosting 38 jQuery test

Slide 39

Slide 39 text

Using jQuery • In most cases, your code should run when the document has finished loading 39 $(document).ready(function(){ // your code should go here }); // alternatively $(function(){ // your code should go here });

Slide 40

Slide 40 text

What is $? • $ is an alias to jQuery • Code can either use $ or just jQuery 40 $(document).ready(function(){ //your code should go here }); // same as.. jQuery(document).ready(function(){ //your code should go here });

Slide 41

Slide 41 text

jQuery Structure • Core • CSS • Selectors • Ajax • Attributes • Effects • Properties 41 • Deferred Object • Dimensions • Events • Manipulation • Plugins • Utilities • Data

Slide 42

Slide 42 text

42 ‘I want to select an element on a page...then do something with it’

Slide 43

Slide 43 text

Basic Selectors Simple selectors for querying elements from the DOM

Slide 44

Slide 44 text

Code 44 //Basic selectors // ID $('#conference') // class $('.attendee') // element $('div') //wildcard $('*') //attribute $('input[name="attendeeName"]')
  • Addy
  • Dan Heberden
  • Adam Sontag
  • Mathias Bynens
  • Douglas

Slide 45

Slide 45 text

Code 45 //Basic selectors // ID $('#conference') // class $('.attendee') // element $('div') //wildcard $('*') //attribute $('input[name="attendeeName"]')
  • Addy
  • Dan Heberden
  • Adam Sontag
  • Mathias Bynens
  • Douglas

Slide 46

Slide 46 text

Code 46 //Basic selectors // ID $('#conference') // class $('.attendee') // element $('div') //wildcard $('*') //attribute $('input[name="attendeeName"]')
  • Addy
  • Dan Heberden
  • Adam Sontag
  • Mathias Bynens
  • Douglas

Slide 47

Slide 47 text

Code 47 //Basic selectors // ID $('#conference') // class $('.attendee') // element $('div') //wildcard $('*') //attribute $('input[name="attendeeName"]')
  • Addy
  • Dan Heberden
  • Adam Sontag
  • Mathias Bynens
  • Douglas

Slide 48

Slide 48 text

Code 48 //Basic selectors // ID $('#conference') // class $('.attendee') // element $('div') //wildcard $('*') //attribute $('input[name="attendeeName"]')
  • Addy
  • Dan Heberden
  • Adam Sontag
  • Mathias Bynens
  • Douglas

Slide 49

Slide 49 text

Code 49 //Basic selectors // ID $('#conference') // class $('.attendee') // element $('div') //wildcard $('*') //attribute $('input[name="attendeeName"]')
  • Addy
  • Dan Heberden
  • Adam Sontag
  • Mathias Bynens
  • Douglas

Slide 50

Slide 50 text

50 ‘What if I want to select an element that’s a child of another element?...’

Slide 51

Slide 51 text

Filter Selectors Selectors for filtering down jQuery collections further

Slide 52

Slide 52 text

Code 52 // Filter selectors //first element in a result set $('ul li:first') //first child of the parent $('ul li:first-child') //last element in a result set $('ul li:last') //last child of the parent $('ul li:last-child') //all odd elements in a result set $('ul li:odd') //all even elements in a result set $('ul li:even')
  • Addy
  • Dan Heberden
  • Adam Sontag
  • Mathias Bynens
  • Douglas

Slide 53

Slide 53 text

Code 53 // Filter selectors //first element in a result set $('ul li:first') //first child of the parent $('ul li:first-child') //last element in a result set $('ul li:last') //last child of the parent $('ul li:last-child') //all odd elements in a result set $('ul li:odd') //all even elements in a result set $('ul li:even')
  • Addy
  • Dan Heberden
  • Adam Sontag
  • Mathias Bynens
  • Douglas

Slide 54

Slide 54 text

Code 54 // Filter selectors //first element in a result set $('ul li:first') //first child of the parent $('ul li:first-child') //last element in a result set $('ul li:last') //last child of the parent $('ul li:last-child') //all odd elements in a result set $('ul li:odd') //all even elements in a result set $('ul li:even')
  • Addy
  • Dan Heberden
  • Adam Sontag
  • Mathias Bynens
  • Douglas

Slide 55

Slide 55 text

Code 55 // Filter selectors //first element in a result set $('ul li:first') //first child of the parent $('ul li:first-child') //last element in a result set $('ul li:last') //last child of the parent $('ul li:last-child') //all odd elements in a result set $('ul li:odd') //all even elements in a result set $('ul li:even')
  • Addy
  • Dan Heberden
  • Adam Sontag
  • Mathias Bynens
  • Douglas

Slide 56

Slide 56 text

Code 56 // Filter selectors //first element in a result set $('ul li:first') //first child of the parent $('ul li:first-child') //last element in a result set $('ul li:last') //last child of the parent $('ul li:last-child') //all odd elements in a result set $('ul li:odd') //all even elements in a result set $('ul li:even')
  • Addy
  • Dan Heberden
  • Adam Sontag
  • Mathias Bynens
  • Douglas

Slide 57

Slide 57 text

Code 57 // Filter selectors //first element in a result set $('ul li:first') //first child of the parent $('ul li:first-child') //last element in a result set $('ul li:last') //last child of the parent $('ul li:last-child') //all odd elements in a result set $('ul li:odd') //all even elements in a result set $('ul li:even')
  • Addy
  • Dan Heberden
  • Adam Sontag
  • Mathias Bynens
  • Douglas

Slide 58

Slide 58 text

Code 58 // Filter selectors //first element in a result set $('ul li:first') //first child of the parent $('ul li:first-child') //last element in a result set $('ul li:last') //last child of the parent $('ul li:last-child') //all odd elements in a result set $('ul li:odd') //all even elements in a result set $('ul li:even')
  • Addy
  • Dan Heberden
  • Adam Sontag
  • Mathias Bynens
  • Douglas

Slide 59

Slide 59 text

Hierarchal Selectors Parent/child selectors

Slide 60

Slide 60 text

Code 60 // Parent/child selectors // a b, returns children of the // parent a $('ul li') // a > b returns elements that are a // child element of a $('body > ul') // returns the elements that are // adjacent to the selector $('label + input') // a ~ b, returns b elements that // are a sibling of a $('p ~ ul')

  • Addy
  • Dan Heberden
  • Adam Sontag
  • Mathias Bynens
  • Douglas
Conference newsletter:

Slide 61

Slide 61 text

Code 61 // Parent/child selectors // a b, returns children of the // parent a $('ul li') // a > b returns elements that are a // child element of a $('body > ul') // returns the elements that are // adjacent to the selector $('label + input') // a ~ b, returns b elements that // are a sibling of a $('p ~ ul')

  • Addy
  • Dan Heberden
  • Adam Sontag
  • Mathias Bynens
  • Douglas
Conference newsletter:

Slide 62

Slide 62 text

Code 62 // Parent/child selectors // a b, returns children of the // parent a $('ul li') // a > b returns elements that are a // child element of a $('body > ul') // returns the elements that are // adjacent to the selector $('label + input') // a ~ b, returns b elements that // are a sibling of a $('p ~ ul')

  • Addy
  • Dan Heberden
  • Adam Sontag
  • Mathias Bynens
  • Douglas
Conference newsletter:

Slide 63

Slide 63 text

Code 63 // Parent/child selectors // a b, returns children of the // parent a $('ul li') // a > b returns elements that are a // child element of a $('body > ul') // returns the elements that are // adjacent to the selector $('label + input') // a ~ b, returns b elements that // are a sibling of a $('p ~ ul')

  • Addy
  • Dan Heberden
  • Adam Sontag
  • Mathias Bynens
  • Douglas
Conference newsletter:

Slide 64

Slide 64 text

Code 64 // Parent/child selectors // a b, returns children of the // parent a $('ul li') // a > b returns elements that are a // child element of a $('body > ul') // returns the elements that are // adjacent to the selector $('label + input') // a ~ b, returns b elements that // are a sibling of a $('p ~ ul')

  • Addy
  • Dan Heberden
  • Adam Sontag
  • Mathias Bynens
  • Douglas
Conference newsletter:

Slide 65

Slide 65 text

65 ‘I work with forms. Anything that can help selections there?’

Slide 66

Slide 66 text

Form Filters Selectors for handling form elements (e.g. inputs, password fields, checkbox etc.)

Slide 67

Slide 67 text

Code 67 //form filters //returns elements that are enabled $('input:enabled') //returns elements that are enabled $('input:disabled') //returns checked items $(':checked') //returns selected items $('select option:selected')
Apple iPad Google Chromebook

Slide 68

Slide 68 text

Code 68 //form filters //returns elements that are enabled $('input:enabled') //returns elements that are enabled $('input:disabled') //returns checked items $(':checked') //returns selected items $('select option:selected')
Apple iPad Google Chromebook

Slide 69

Slide 69 text

Code 69 //form filters //returns elements that are enabled $('input:enabled') //returns elements that are enabled $('input:disabled') //returns checked items $(':checked') //returns selected items $('select option:selected')
Apple iPad Google Chromebook

Slide 70

Slide 70 text

Code 70 //form filters //returns elements that are enabled $('input:enabled') //returns elements that are enabled $('input:disabled') //returns checked items $(':checked') //returns selected items $('select option:selected')
Apple iPad Google Chromebook

Slide 71

Slide 71 text

Code 71 //form filters //returns elements that are enabled $('input:enabled') //returns elements that are enabled $('input:disabled') //returns checked items $(':checked') //returns selected items $('select option:selected')
Apple iPad Google Chromebook

Slide 72

Slide 72 text

72 “I’d like to select elements using indices or equations. Can you help?”

Slide 73

Slide 73 text

nth-child Filters Filtering using the CSS nth-child selector

Slide 74

Slide 74 text

Code 74 //nth-child filters //nth child in a result set $('ul li:nth-child(2)') //all odd numbered results $('ul li:nth-child(odd)') //all even numbered results $('ul li:nth-child(even)') //all elements based on a formula. here it’s every 2nd child $('ul li:nth-child(2n)')
  • Addy
  • Dan Heberden
  • Adam Sontag
  • Mathias Bynens
  • Douglas

Slide 75

Slide 75 text

Code 75 //nth-child filters //nth child in a result set $('ul li:nth-child(2)') //all odd numbered results $('ul li:nth-child(odd)') //all even numbered results $('ul li:nth-child(even)') //all elements based on a formula. here it’s every 2nd child $('ul li:nth-child(2n)')
  • Addy
  • Dan Heberden
  • Adam Sontag
  • Mathias Bynens
  • Douglas

Slide 76

Slide 76 text

Code 76 //nth-child filters //nth child in a result set $('ul li:nth-child(2)') //all odd numbered results $('ul li:nth-child(odd)') //all even numbered results $('ul li:nth-child(even)') //all elements based on a formula. here it’s every 2nd child $('ul li:nth-child(2n)')
  • Addy
  • Dan Heberden
  • Adam Sontag
  • Mathias Bynens
  • Douglas

Slide 77

Slide 77 text

Code 77 //nth-child filters //nth child in a result set $('ul li:nth-child(2)') //all odd numbered results $('ul li:nth-child(odd)') //all even numbered results $('ul li:nth-child(even)') //all elements based on a formula. here it’s every 2nd child $('ul li:nth-child(2n)')
  • Addy
  • Dan Heberden
  • Adam Sontag
  • Mathias Bynens
  • Douglas

Slide 78

Slide 78 text

Code 78 //nth-child filters //nth child in a result set $('ul li:nth-child(2)') //all odd numbered results $('ul li:nth-child(odd)') //all even numbered results $('ul li:nth-child(even)') //all elements based on a formula. here it’s every 2nd child $('ul li:nth-child(2n)')
  • Addy
  • Dan Heberden
  • Adam Sontag
  • Mathias Bynens
  • Douglas

Slide 79

Slide 79 text

More Pseudo Selectors Selectors for handling whether selectors are visible or hidden and more

Slide 80

Slide 80 text

Code 80 //more pseudo selectors // returns elements that are hidden $('li:hidden') // returns elements that are visible $('li:visible') // returns elements that don't match // the condition supplied $('input:not(:checked)') // returns elements that are equal to // the index supplied $('ul li:eq(1)') // returns elements that are greather // than the index supplied $('ul li:gt(2)') // returns elements in a set less than // the index supplied $('ul li:lt(2)') .hidden{ display:none}
  • Dan Heberden
  • Mathias Bynens
  • Douglas

Slide 81

Slide 81 text

Code 81 //more pseudo selectors // returns elements that are hidden $('li:hidden') // returns elements that are visible $('li:visible') // returns elements that don't match // the condition supplied $('input:not(:checked)') // returns elements that are equal to // the index supplied $('ul li:eq(1)') // returns elements that are greather // than the index supplied $('ul li:gt(2)') // returns elements in a set less than // the index supplied $('ul li:lt(2)') .hidden{ display:none}
  • Dan Heberden
  • Mathias Bynens
  • Douglas

Slide 82

Slide 82 text

Code 82 //more pseudo selectors // returns elements that are hidden $('li:hidden') // returns elements that are visible $('li:visible') // returns elements that don't match // the condition supplied $('input:not(:checked)') // returns elements that are equal to // the index supplied $('ul li:eq(1)') // returns elements that are greather // than the index supplied $('ul li:gt(2)') // returns elements in a set less than // the index supplied $('ul li:lt(2)') .hidden{ display:none}
  • Dan Heberden
  • Mathias Bynens
  • Douglas

Slide 83

Slide 83 text

Code 83 //more pseudo selectors // returns elements that are hidden $('li:hidden') // returns elements that are visible $('li:visible') // returns elements that don't match // the condition supplied $('input:not(:checked)') // returns elements that are equal to // the index supplied $('ul li:eq(1)') // returns elements that are greather // than the index supplied $('ul li:gt(2)') // returns elements in a set less than // the index supplied $('ul li:lt(2)') .hidden{ display:none}
  • Dan Heberden
  • Mathias Bynens
  • Douglas

Slide 84

Slide 84 text

Code 84 //more pseudo selectors // returns elements that are hidden $('li:hidden') // returns elements that are visible $('li:visible') // returns elements that don't match // the condition supplied $('input:not(:checked)') // returns elements that are equal to // the index supplied $('ul li:eq(1)') // returns elements that are greather // than the index supplied $('ul li:gt(2)') // returns elements in a set less than // the index supplied $('ul li:lt(2)') .hidden{ display:none}
  • Dan Heberden
  • Mathias Bynens
  • Douglas

Slide 85

Slide 85 text

Code 85 //more pseudo selectors // returns elements that are hidden $('li:hidden') // returns elements that are visible $('li:visible') // returns elements that don't match // the condition supplied $('input:not(:checked)') // returns elements that are equal to // the index supplied $('ul li:eq(1)') // returns elements that are greather // than the index supplied $('ul li:gt(2)') // returns elements in a set less than // the index supplied $('ul li:lt(2)') .hidden{ display:none}
  • Dan Heberden
  • Mathias Bynens
  • Douglas

Slide 86

Slide 86 text

Code 86 //more pseudo selectors // returns elements that are hidden $('li:hidden') // returns elements that are visible $('li:visible') // returns elements that don't match // the condition supplied $('input:not(:checked)') // returns elements that are equal to // the index supplied $('ul li:eq(1)') // returns elements that are greather // than the index supplied $('ul li:gt(2)') // returns elements in a set less than // the index supplied $('ul li:lt(2)') .hidden{ display:none}
  • Dan Heberden
  • Mathias Bynens
  • Douglas

Slide 87

Slide 87 text

87 ‘What about elements containing some specific text or elements?’

Slide 88

Slide 88 text

Content Filters Filters for narrowing down elements with specific content

Slide 89

Slide 89 text

Code 89 //content filters // :has(a) all elements with a descendant that matches a $('div:has(p)') //:contains(a) the element contains a $('li:contains("Dan")') //returns elements that are empty $(':empty') //returns the parent of li $('li:parent')

attendee

  • Addy
  • Dan Heberden
  • Mathias Bynens
  • Douglas

Slide 90

Slide 90 text

Code 90 //content filters // :has(a) all elements with a descendant that matches a $('div:has(p)') //:contains(a) the element contains a $('li:contains("Dan")') //returns elements that are empty $(':empty') //returns the parent of li $('li:parent')

attendee

  • Addy
  • Dan Heberden
  • Mathias Bynens
  • Douglas

Slide 91

Slide 91 text

Code 91 //content filters // :has(a) all elements with a descendant that matches a $('div:has(p)') //:contains(a) the element contains a $('li:contains("Dan")') //returns elements that are empty $(':empty') //returns the parent of li $('li:parent')

attendee

  • Addy
  • Dan Heberden
  • Mathias Bynens
  • Douglas

Slide 92

Slide 92 text

Code 92 //content filters // :has(a) all elements with a descendant that matches a $('div:has(p)') //:contains(a) the element contains a $('li:contains("Dan")') //returns elements that are empty $(':empty') //returns the parent of li $('li:parent')

attendee

  • Addy
  • Dan Heberden
  • Mathias Bynens
  • Douglas

Slide 93

Slide 93 text

Code 93 //content filters // :has(a) all elements with a descendant that matches a $('div:has(p)') //:contains(a) the element contains a $('li:contains("Dan")') //returns elements that are empty $(':empty') //returns the parent of li $('li:parent')

attendee

  • Addy
  • Dan Heberden
  • Mathias Bynens
  • Douglas

Slide 94

Slide 94 text

jQuery Collections Understanding what $() returns

Slide 95

Slide 95 text

Code 95 // Collections // this returns a jQuery collection // your selection wrapped inside a // jQuery object that can be further // manipulated $('ul li') // we can treat it a little like an array $('ul li').length //5 // we can iterate over it.. $('ul li').each(function(i, x){ console.log($(this)); }); // and we can also call methods on it $('ul li').hide(); //hides these elements
  • Addy
  • Dan Heberden
  • Adam Sontag
  • Mathias Bynens
  • Douglas

Slide 96

Slide 96 text

96 “I’ve heard you can chain methods with jQuery...how does that work? Why would I use it?”

Slide 97

Slide 97 text

Method Chaining Chaining method calls to write shorter, less repetitive code

Slide 98

Slide 98 text

Code 98 // Chaining // When you call a method on // a jQuery object another // jQuery object is usually returned // Because of this, we're able to // easily 'chain' together methods $('ul') .find('.attendee') .addClass('arrived') .removeClass('pending');
  • Addy
  • Dan Heberden
  • Adam Sontag
  • Mathias Bynens
  • Douglas

Slide 99

Slide 99 text

Code 99 // Accessing the original selection // We sometimes want to access the // original selection again and we // can use .end() to achieve this.. $('ul') .find('.attendee') .addClass('arrived') .removeClass('pending') .end() .addClass('seated');
  • Addy
  • Dan Heberden
  • Adam Sontag
  • Mathias Bynens
  • Douglas

Slide 100

Slide 100 text

100 ‘Do I re-query the DOM every time I want to do something with an element?’

Slide 101

Slide 101 text

Caching How to avoid re-querying the DOM unless absolutely necessary

Slide 102

Slide 102 text

jQuery • jQuery makes selecting elements simple • However, behind the scenes a lot of work can be involved in querying the DOM • By caching selections, we avoid having to re- query the DOM unless necessary 102

Slide 103

Slide 103 text

Code 103 // uncached selections $('.attendee').fadeIn(); $('.attendee').css('color','green'); $('.attendee').on('click',function(){ console.log('hello world'); })
  • Addy
  • Dan Heberden
  • Adam Sontag
  • Mathias Bynens
  • Douglas

Slide 104

Slide 104 text

Code 104 // uncached selections $('.attendee').fadeIn(); $('.attendee').css('color','green'); $('.attendee').on('click',function(){ console.log('hello world'); })
  • Addy
  • Dan Heberden
  • Adam Sontag
  • Mathias Bynens
  • Douglas

Slide 105

Slide 105 text

Code 105 // cache the selection var attendees = $('.attendee'); // use as needed attendees.fadeIn(); attendees.css('color','green'); attendees.on('click', function(){ console.log('hello world'); });
  • Addy
  • Dan Heberden
  • Adam Sontag
  • Mathias Bynens
  • Douglas

Slide 106

Slide 106 text

Code 106 //but this also supports chaining! var attendees = $('.attendee'); attendees .fadeIn() .css('color','green') .on('click', function(){ console.log('hello world'); });
  • Addy
  • Dan Heberden
  • Adam Sontag
  • Mathias Bynens
  • Douglas

Slide 107

Slide 107 text

107 ‘How do I modify the style of elements using jQuery?’

Slide 108

Slide 108 text

CSS Methods for getting and setting CSS-related properties of elements

Slide 109

Slide 109 text

As we saw earlier.. –With JavaScript, you would style elements like this.. 109 var elems = document.getElementsByClassName('attendee'), len = elems.length, i=0; for(; i

Slide 110

Slide 110 text

But.. –With jQuery, it’s just a simple one-liner: 110 $('.attendee').css('backgroundColor','orange'); before a2er

Slide 111

Slide 111 text

The .css() method • Supports a few different signatures: –$(elem).css(name) - gets a CSS property –$(elem).css(name, value) - sets a property –$(elem).css({multiple properties}) - set multiple properties and values 111

Slide 112

Slide 112 text

CSS • We also support some other utility methods: –$(elem).addClass(‘className’); –$(elem).removeClass(‘className’); –$(elem).toggleClass(‘className’); –and more!. 112

Slide 113

Slide 113 text

Code 113 $(‘.attendee’) .removeClass(‘arrived’) .addClass(‘attending’) .css({ ‘font-size’:‘20px’, ‘color’:‘orange’, ‘border’:‘1px solid black’, }) .toggleClass(‘seated’); AFendee AFendee AFendee AFendee AFendee AFendee

Slide 114

Slide 114 text

Code 114 $(‘.attendee’) .removeClass(‘arrived’) .addClass(‘attending’) .css({ ‘font-size’:‘20px’, ‘color’:‘orange’, ‘border’:‘1px solid black’, }) .toggleClass(‘seated’); AFendee AFendee AFendee AFendee AFendee AFendee

Slide 115

Slide 115 text

Code 115 $(‘.attendee’) .removeClass(‘arrived’) .addClass(‘attending’) .css({ ‘font-size’:‘20px’, ‘color’:‘orange’, ‘border’:‘1px solid black’, }) .toggleClass(‘seated’); AFendee AFendee AFendee AFendee AFendee AFendee

Slide 116

Slide 116 text

Code 116 $(‘.attendee’) .removeClass(‘arrived’) .addClass(‘attending’) .css({ ‘font-size’:‘20px’, ‘color’:‘orange’, ‘border’:‘1px solid black’, }) .toggleClass(‘seated’); AFendee AFendee AFendee AFendee AFendee AFendee

Slide 117

Slide 117 text

Code 117 $(‘.attendee’) .removeClass(‘arrived’) .addClass(‘attending’) .css({ ‘font-size’:‘20px’, ‘color’:‘orange’, ‘border’:‘1px solid black’, }) .toggleClass(‘seated’); AFendee AFendee AFendee AFendee AFendee AFendee

Slide 118

Slide 118 text

Code 118 var attendees = $('.attendee'), // Returns 'orange' currentTextColor = attendees.css('color'), // Returns '1px solid black' currentBorder = attendees.css('border'), // Returns '20px' currentFontSize = attendees.css('font-size'); AFendee AFendee AFendee AFendee AFendee AFendee

Slide 119

Slide 119 text

Code 119 // Single property changes $('#container').css('backgroundColor','orange'); // Multiple property changes $('.attendee').css({ 'width':'200', 'height':'100', 'color':'red', 'backgroundColor':'blue' }); // Working with cached elements var myDiv = $('div'); myDiv.css('color','green');

Slide 120

Slide 120 text

120 ‘I want things to swoosh from one side to another or just fade in. How can I animate?’

Slide 121

Slide 121 text

Effects Short-hand and long-hand approaches for animating elements

Slide 122

Slide 122 text

Animation • There are both short-hand and long-hand methods of doing animation: • $(elem).show() • $(elem).hide() • $(elem).fadeIn() • $(elem).fadeOut() • $(elem).animate() 122

Slide 123

Slide 123 text

Short-hand: Hide and Show 123 // cache the selection var attendees = $('.attendee'); // Hide all attendees attendees.hide();
  • Addy
  • Dan Heberden
  • Adam Sontag
  • Mathias Bynens
  • Douglas

Slide 124

Slide 124 text

Short-hand: Hide and Show 124 // cache the selection var attendees = $('.attendee'); // Show all attendees attendees.show();
  • Addy
  • Dan Heberden
  • Adam Sontag
  • Mathias Bynens
  • Douglas

Slide 125

Slide 125 text

Short-hand: Fade-in/Fade-out 125 // cache the selection var attendees = $('.attendee'); // Fade-out all attendees attendees.fadeOut(); // Fade-in all attendees attendees.fadeIn();
  • Addy
  • Dan Heberden
  • Adam Sontag
  • Mathias Bynens
  • Douglas

Slide 126

Slide 126 text

Short-hand: A little better 126 // cache the selection var attendees = $('.attendee'); // Show all attendees over time attendees.show(500, function(){ alert(‘there you are!’); }); // Fade-out all attendees over time attendees.fadeOut(500, function(){ alert(‘you disappeared!’); });
  • Addy
  • Dan Heberden
  • Adam Sontag
  • Mathias Bynens
  • Douglas

Slide 127

Slide 127 text

Long-hand: animate() 127 attendees.animate({ 'width': '200', 'height': '300', 'opacity': '0.5', 'marginLeft': '20' }, 200, function(){ //animation complete });

Slide 128

Slide 128 text

Long-hand: animate() 128 attendees.animate({ 'width': '200', 'height': '300', 'opacity': '0.5', 'marginLeft': '20' }, 200, function(){ //animation complete }); What  would  you  like  to  animate?

Slide 129

Slide 129 text

Long-hand: animate() 129 attendees.animate({ 'width': '200', 'height': '300', 'opacity': '0.5', 'marginLeft': '20' }, 200, function(){ //animation complete }); DuraAon  for  the  animaAon  (ms)

Slide 130

Slide 130 text

Long-hand: animate() 130 attendees.animate({ 'width': '200', 'height': '300', 'opacity': '0.5', 'marginLeft': '20' }, 200, function(){ //animation complete }); Callback  funcAon  for  when  the animaAon  completes.

Slide 131

Slide 131 text

Step-functions: 131 attendees.animate({ opacity: '0.5', height: '50%' },{ // step: a callback function fired at // each step of an animation step: function(now, fx) { var data = fx.elem.id + ' ' + fx.prop + ': ' + now; $('body').append('
' + data + '
'); } });

Slide 132

Slide 132 text

Easing functions: 132 $('#container').animate({ width: ['toggle', 'swing'], height: ['toggle', 'swing'], opacity: 'toggle' }, 500, 'linear', function() { $(this).after('
Animation complete.
'); });

Slide 133

Slide 133 text

Easing functions: 133 $('#container').animate({ width: ['toggle', 'swing'], height: ['toggle', 'swing'], opacity: 'toggle' }, 500, // an easing function that sets the speed at which the // animation progresses at different points in the // animation. Think of 'linear' as smooth. 'linear', function() { $(this).after('
Animation complete.
'); });

Slide 134

Slide 134 text

134 “I want to get or post content using Ajax, so I don’t have to reload the page. Is that hard to do?”

Slide 135

Slide 135 text

Ajax Performing asynchronous HTTP requests

Slide 136

Slide 136 text

Ajax • jQuery supports both short and long-hand methods for making Ajax requests • $.get() • $.post() • $.getJSON() • $.ajax() • and others • Cross-browser XHR without the headaches! 136

Slide 137

Slide 137 text

Short-hand: Get and Post 137 // Get data $.get('attendees.html', function( data ) { $('.result').html(data); }); // Post data $.post('attendees.php', { name: ‘John’ }, function( data ){ $('.result').html(data); });

Slide 138

Slide 138 text

Short-hand: Get and Post 138 // Get data $.get('attendees.html', function( data ) { $('.result').html( data ); }); // Post data $.post('attendees.php', { name: ‘John’ }, function( data ){ $('.result').html( data ); });

Slide 139

Slide 139 text

Short-hand: Get JSON 139 $.getJSON('attendees.json', function( data ) { var attendees = []; $.each( data, function( key, val ) { attendees.push('
  • ' + val +'
  • '); }); $('
      ', { 'class': 'attendees', html: attendees.join('') }).appendTo('body'); });

      Slide 140

      Slide 140 text

      Getting JSON 140 $.getJSON('attendees.json', function( data ) { var attendees = []; $.each( data, function( key, val ) { attendees.push('
    • ' + val +'
    • '); }); $('
        ', { 'class': 'attendees', html: attendees.join('') }).appendTo('body'); }); IteraAng  over  our  data and  pushing  into  an  array

        Slide 141

        Slide 141 text

        Getting JSON 141 $.getJSON('attendees.json', function( data ) { var attendees = []; $.each( data, function( key, val ) { attendees.push('
      • ' + val +'
      • '); }); $('
          ', { 'class': 'attendees', html: attendees.join('') }).appendTo('body'); }); Dynamically  generate  a  list containing  our  items  and   append  to  the  document   body

          Slide 142

          Slide 142 text

          Ajax: Retrieving content 142 // Retrieve the latest version of a web page $.ajax({ url: "attendees.html", cache: false, // What to do if this is successful: success: function(html){ $("#results").append(html); }, // What to do if this fails: error: function(){ //something went wrong } });

          Slide 143

          Slide 143 text

          Ajax: Retrieving content 143 // Retrieve the latest version of a web page $.ajax({ url: "attendees.html", cache: false, // What to do if this is successful: success: function(html){ $("#results").append(html); }, // What to do if this fails: error: function(){ //something went wrong } });

          Slide 144

          Slide 144 text

          Ajax: Retrieving content 144 // Retrieve the latest version of a web page $.ajax({ url: "attendees.html", cache: false, // What to do if this is successful: success: function(html){ $("#results").append(html); }, // What to do if this fails: error: function(){ //something went wrong } });

          Slide 145

          Slide 145 text

          Ajax: Retrieving content 145 // More future-proof version: var jqxhr = $.ajax({ url: "attendees.html", cache: false }) .done(function(){ // success! }) .fail"(function(){ // error! }); // Better as .success() and .error() are going.

          Slide 146

          Slide 146 text

          Ajax: We also support.. 146 var request = $.ajax({ url: 'attendees.html', type: 'POST', data: {id : attendeeID}, dataType: 'html', cache: 'false' }); request.done(function(data){ console.log('Received:' + data); }); request.fail(function(data, status){ console.log('failed because:' + status); });

          Slide 147

          Slide 147 text

          Advanced Ajax: Deferreds 147 // Let’s make a request for a file function getFile(){ return $.get('attendees.html'); } // All $.ajax/short-hand ajax methods support returning // a promise for something to be completed. This allows us // to make non-blocking calls to servers. $.when( getFile() ) .then(function(){ console.log( 'I fire when getFile() has completed!' ); }) .fail(function(){ console.log( 'I fire if requests fail!' ); }); // Read the above as ‘when’ getFile() is resolved, then do something. If this fails do something else.

          Slide 148

          Slide 148 text

          148 “How do I attach events to elements? I’d like to have something happen when I click or hover over them”

          Slide 149

          Slide 149 text

          Events Registering behaviours which are applied when a user interacts with the browser

          Slide 150

          Slide 150 text

          jQuery • Before jQuery 1.7: –Many ways to attach event handlers to elements • .bind() - basic attachment of a handler to an element • .delegate() - supports attaching handlers to elements that have been added dynamically after page-load. • .live() - similar to delegate, but not as great with larger groups of elements. –and the following for ‘unbinding’ handlers: • .unbind() • .undelegate() 150

          Slide 151

          Slide 151 text

          151 ‘Whoa. Wait...three methods? But how do I know which to use? Couldn’t this be made simpler?’

          Slide 152

          Slide 152 text

          jQuery • As of jQuery 1.7: –We now have: • .on() –and unbind.. • .off() –for all possible cases –Much simpler to understand. 152

          Slide 153

          Slide 153 text

          Code 153 // Binding a click event to elements // with the class 'attendee' $('.attendee').on('click', function(){ $(this).css('color','red'); }); // Remove just the click event handler $('.attendee').off('click','**'); // Remove all event handlers from // attendees e.g. if others had been // set $('.attendee').off();

          Slide 154

          Slide 154 text

          Binding: Same syntax 154 // Old way of doing things $('a').bind('click', myHandler); $('form') .bind('submit', { val: 42 }, fn); $('.comment') .delegate('a.add', 'click', addNew); $('.dialog') .undelegate('a', 'click.myDlg'); $('a').live('click', fn); $('a').die('click'); // The new, simpler, hotness $('a').on('click', myHandler); $('form') .on('submit', { val: 42 }, fn); $('.comment') .on('click', 'a.add', addNew); $('.dialog') .off('click.myDlg', 'a'); $(document).on('click', 'a', fn); $(document).off('click', 'a');

          Slide 155

          Slide 155 text

          Delegation: Order changes 155 // Old way of doing things $('a').bind('click', myHandler); $('form') .bind('submit', { val: 42 }, fn); $('.comment') .delegate('a.add', 'click', addNew); $('.dialog') .undelegate('a', 'click.myDlg'); $('a').live('click', fn); $('a').die('click'); // The new, simpler, hotness $('a').on('click', myHandler); $('form') .on('submit', { val: 42 }, fn); $('.comment') .on('click', 'a.add', addNew); $('.dialog') .off('click.myDlg', 'a'); $(document).on('click', 'a', fn); $(document).off('click', 'a');

          Slide 156

          Slide 156 text

          Live: More minor changes 156 // Old way of doing things $('a').bind('click', myHandler); $('form') .bind('submit', { val: 42 }, fn); $('.comment') .delegate('a.add', 'click', addNew); $('.dialog') .undelegate('a', 'click.myDlg'); $('a').live('click', fn); $('a').die('click'); // The new, simpler, hotness $('a').on('click', myHandler); $('form') .on('submit', { val: 42 }, fn); $('.comment') .on('click', 'a.add', addNew); $('.dialog') .off('click.myDlg', 'a'); $(document).on('click', 'a', fn); $(document).off('click', 'a');

          Slide 157

          Slide 157 text

          Code: Prevent defaults 157 // .preventDefault() allows us to cancel // only the *default* action $("form").on("submit", function(event) { event.preventDefault(); }); // .stopPropagation() allows us to stop // events from bubbling without preventing // the standard form submit $("form").on("submit", function(event) { event.stopPropagation(); });

          Slide 158

          Slide 158 text

          Code: Prevent defaults 158 // .preventDefault() allows us to cancel // only the *default* action $("form").on("submit", function(event) { event.preventDefault(); }); // .stopPropagation() allows us to stop // events from bubbling without preventing // the standard form submit $("form").on("submit", function(event) { event.stopPropagation(); });

          Slide 159

          Slide 159 text

          159 “I usually just store information in variables, but I’d like to associate data with elements. Can jQuery help?”

          Slide 160

          Slide 160 text

          Data Storing and retrieving arbitrary data using specific DOM elements

          Slide 161

          Slide 161 text

          jQuery • jQuery has an internal data cache: –Can be used to store data in key/value pairs –Data is stored against any DOM elements –Data can be stored and retrieved, a little like a database (store) 161

          Slide 162

          Slide 162 text

          Code 162 var last = $('.attendee:last'); // Set some data with $.fn.data() last.data('firstName', 'John'); last.data('lastName', 'Resig'); // You can then access this data // as follows: console.log( last.data('firstName') );
          • Addy
          • Dan Heberden
          • Adam Sontag
          • Mathias Bynens
          • Douglas

          Slide 163

          Slide 163 text

          Code 163 // utility methods // May be deprecated in the future // or moved to plugins // does the DOM node or object // have data attached? $.hasData(lastAttendee); //true // Removes data stored under // a specific key $.removeData(lastAttendee, 'firstName'); //removes all data $.removeData(lastAttendee); // Lower level data method for // handling data associated with // an element $.data('.attendee:first', 'foo', 'bar'); //same as elem.data('foo','bar')
          • Addy
          • Dan Heberden
          • Adam Sontag
          • Mathias Bynens
          • Douglas

          Slide 164

          Slide 164 text

          164 “I want to iterate through the elements returned by a selector. How can I do that?”

          Slide 165

          Slide 165 text

          Utilities Iterating over collections and traversing the DOM for other subsets of collections

          Slide 166

          Slide 166 text

          Code 166 //Iterators // .each() $(‘li’).each(function(index)){ alert(index + ': ' + $(this).text ()); }); // but if we want to pass each // element through a function.. // .map() $(".welcome") .append( $(“li").map(function(){ return $(this).val(); }) .get() .join(", ") ); // appends comma-separated list of li values
          • Addy
          • Dan Heberden
          • Adam Sontag
          • Mathias Bynens
          • Douglas

          Slide 167

          Slide 167 text

          Code 167 //Iterators // .each() $(‘li’).each(function(index)){ alert(index + ': ' + $(this).text ()); }); // but if we want to pass each // element through a function.. // .map() $(".welcome") .append( $(“li").map(function(){ return $(this).val(); }) .get() .join(", ") ); // appends comma-separated list of li values
          • Addy
          • Dan Heberden
          • Adam Sontag
          • Mathias Bynens
          • Douglas

          Slide 168

          Slide 168 text

          168 “I want to be able to check if something has been ‘checked’ or modify attributes like ‘href’. Can I?”

          Slide 169

          Slide 169 text

          Attributes Getting and settings DOM attributes of elements

          Slide 170

          Slide 170 text

          jQuery • jQuery supports getting and setting DOM attributes and properties of elements –attributes are generally strings –can be modified via .attr() –properties can be modified via .prop() 170

          Slide 171

          Slide 171 text

          Code 171 // .attr() gets the attribute value // for the first element in a set only // gets the value of an attribute $('a').attr('href'); // sets the value of an attribute $('a').attr('href','http://google.com'); // we can also set multiple // attributes at the same time $('a').attr({ title: 'Google!', alt: 'Googling', href: 'http://google.com' });
          • Addy
          • Dan Heberden
          • Adam Sontag
          • Mathias Bynens
          • Douglas

          Slide 172

          Slide 172 text

          jQuery • Only thing that can’t be altered like this is type • Some browsers throw errors when this is attempted to be changed • (Mostly IE) 172

          Slide 173

          Slide 173 text

          jQuery • Similar to attributes, jQuery also allows us to get and set properties –Difference is important –‘checked’ is a property –‘title’ is an attribute –Before 1.6, attr() sometimes took properties into account causing inconsistencies –This is now fixed 173

          Slide 174

          Slide 174 text

          Code 174 // Prop examples var elem = $('input'); var node = elem[0]; //true alert( node.checked ); //true elem.prop('checked'); //true elem.is(':checked'); // change prop elem.prop('checked',''); //or elem.removeProp('checked');
          test

          Slide 175

          Slide 175 text

          Summary What did we learn today?

          Slide 176

          Slide 176 text

          176 jQuery can be a powerful addition to your front-end utility belt

          Slide 177

          Slide 177 text

          We covered: • Core concepts –Setup –Selection –Chaining –Caching 177

          Slide 178

          Slide 178 text

          We looked through: • API –Selectors –Events –Animation –Traversing –Attributes –Ajax –and more. 178

          Slide 179

          Slide 179 text

          179 You can start using it right away

          Slide 180

          Slide 180 text

          180 Go try it out at jQuery.com!

          Slide 181

          Slide 181 text

          181 For questions or more from me: @addyosmani or addyosmani.com

          Slide 182

          Slide 182 text

          182 For a free jQuery book check out: jqfundamentals.com