0
JavaScript and jQuery    John Resig - November 2012          Hacker School
JavaScript Language✦   Basics✦   Functions✦   Function Prototypes✦   Closures
The Basics✦   Most akin to most other major languages✦   Looping:    for ( var i = 0; i < 10; i++ ) {} // array    for ( v...
Variable Declaration✦   Variable declaration:    var foo = “bar”;✦   Variables are scoped to the function, not    to the b...
Global Object✦   JavaScript, by itself, isn’t useful    ✦ Just a ‘dumb’ scripting language    ✦ Functionality must be intr...
Primitives✦   Completely dynamic language - no “types”✦   A few primitives:    ✦ Boolean: true / false    ✦ String: “hello...
Objects✦   Object    var obj = { key: “value”, key2: “value2” };    obj.key == “value”;    obj[“key2”] == “value2”;✦   Arr...
Functional✦   JavaScript is a functional language    ✦ Functions are first-class objects✦   function test(){}    test( test...
Function Definition✦   Defining a function makes it omni-    present, within its scope✦   function test() {      return foo(...
Functions as Objects✦   Functions can have properties✦   function test(){}    test.a = 1;    test.b = 2;
Self-Memoization✦   function isPrime( num ) {      if ( isPrime.answers[ num ] != null )        return isPrime.answers[ nu...
Function Context✦   ‘this’ within a function✦   var obj = {      fn: function(){        return this == obj;      }    };  ...
Modify Context✦   [0,1,2].join(“ “) == “0 1 2”✦   [].join.call([0,1,2],” “) == “0 1 2”✦   [].join.call("test"," ") == “t e...
Instantiation✦   No ‘classes’ in JavaScript✦   You can instantiate a function✦   function User( name ){      this.name = n...
Function Prototypes✦   All functions have a prototype property✦   All prototype properties are added to    function instan...
Inheritance✦   Use the prototype to chain functions    together✦   function People(){}    People.prototype.human = true;  ...
instanceof✦   var john = new Resig(“John”);    john instanceof Resig    john instanceof Person    john instanceof Object✦ ...
Native Prototypes✦   You can extend the prototypes of native    functions✦   String.prototype.join = function(array){     ...
✦   Object.prototype.keys = function(){       var a = [];       for ( var i in this )        a.push( i );       return a; ...
Closures✦   Referencing an external variable    encapsulates it for later access✦   function Ninja(){      var slices = 0;...
Currying✦   Pre-fill in arguments to a function,    generating a new function✦   Function.prototype.curry = function() {   ...
DOM
DOM Difficulty✦   JavaScript programming can be hard    ✦ Problem isn’t the JavaScript language    ✦ Cross-browser issues ar...
DOM Methods✦   <div></div>    document.getElementsByTagName(“div”)✦   <div id=”test”></div>    document.getElementById(“te...
JavaScript Libraries✦   Come to the rescue!✦   Drastically simplify DOM, Ajax,    Animations✦   Use a library, like jQuery!
jQuery
What is jQuery?✦   An open source JavaScript library that    simplifies the interaction between HTML    and JavaScript.
Ideal for Prototyping✦   Completely unobtrusive✦   Uses CSS to layer functionality✦   Easy to separate behavior✦   Quick, ...
The Focus of jQueryFind Some Elements Do something with them    {                         {   $(“div”).addClass(“special”)...
The jQuery Object✦   Commonly named ‘$’✦   Also named ‘jQuery’✦   Completely valid:    ✦ jQuery(“div”).addClass(“special”);
Find Some Elements...✦   Full CSS Selector 1-3 Support✦   Basic XPath✦   Better CSS Selector support than most    browsers
$(“div”)<div id=”body”>  <h2>Some Header</h2>  <div class=”contents”>      <p>...</p>      <p>...</p>  </div></div>
$(“#body”)<div id=”body”>  <h2>Some Header</h2>  <div class=”contents”>      <p>...</p>      <p>...</p>  </div></div>
$(“div#body”)<div id=”body”>  <h2>Some Header</h2>  <div class=”contents”>      <p>...</p>      <p>...</p>  </div></div>
$(“div.contents p”)  <div id=”body”>    <h2>Some Header</h2>    <div class=”contents”>        <p>...</p>        <p>...</p>...
$(“div > div”)<div id=”body”>  <h2>Some Header</h2>  <div class=”contents”>      <p>...</p>      <p>...</p>  </div></div>
$(“div:has(div)”) <div id=”body”>   <h2>Some Header</h2>   <div class=”contents”>       <p>...</p>       <p>...</p>   </di...
Do something with them✦   DOM Manipulation (append, prepend, remove)✦   Events (click, hover, toggle)✦   Effects (hide, sho...
DOM Manipulation✦   $(“a[target]”)       .append(“ (Opens in New Window)”);✦   $(“#body”).css({        border: “1px solid ...
Events✦   $(“form”).submit(function(){        if ( $(“input#name”).val() == “” )           $(“span.help”).show();    });✦ ...
Animations✦   $(“#menu”).slideDown(“slow”);✦   Individual properties:    $(“div”).animate({        fontWeight: “2em”,     ...
Ajax✦   $(“#body”).load(“sample.html div > h1”);    ✦ Before:      <div id=”body”></div>    ✦ After:      <div id=”body”> ...
Chaining✦   You can have multiple actions against a single set    of elements✦   $(“div”).hide();✦   $(“div”).hide().css(“...
Chaining (cont.)✦   $(“ul.open”) // [ ul, ul, ul ]       .children(“li”) // [ li, li, li ]          .addClass(“open”) // [...
Questions?  http://ejohn.org/ http://jquery.com/
Upcoming SlideShare
Loading in...5
×

JavaScript and jQuery (Hacker School 2011)

2,073

Published on

0 Comments
5 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
2,073
On Slideshare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
24
Comments
0
Likes
5
Embeds 0
No embeds

No notes for slide

Transcript of "JavaScript and jQuery (Hacker School 2011)"

  1. 1. JavaScript and jQuery John Resig - November 2012 Hacker School
  2. 2. JavaScript Language✦ Basics✦ Functions✦ Function Prototypes✦ Closures
  3. 3. The Basics✦ Most akin to most other major languages✦ Looping: for ( var i = 0; i < 10; i++ ) {} // array for ( var i in obj ) // obj property/value while ( true ) {}✦ Statements: if ( true ) {}
  4. 4. Variable Declaration✦ Variable declaration: var foo = “bar”;✦ Variables are scoped to the function, not to the block✦ function test(){ for ( var i = 0; i < 10; i++ ) {} return i; } test() == 10
  5. 5. Global Object✦ JavaScript, by itself, isn’t useful ✦ Just a ‘dumb’ scripting language ✦ Functionality must be introduced✦ All functionality is contained within the global object (named ‘window’ in browsers)✦ var foo = “test”; window.foo == “test”;
  6. 6. Primitives✦ Completely dynamic language - no “types”✦ A few primitives: ✦ Boolean: true / false ✦ String: “hello” ✦ Number: 4✦ Type cohersion ✦ 0 == false ✦ null == false ✦ !”foo” == false
  7. 7. Objects✦ Object var obj = { key: “value”, key2: “value2” }; obj.key == “value”; obj[“key2”] == “value2”;✦ Array var a = [ 0, 1, 2, 3 ]; a.push( 4 );✦ RegExp /he[l]+o/i.test(“hello”)✦ and Functions!
  8. 8. Functional✦ JavaScript is a functional language ✦ Functions are first-class objects✦ function test(){} test( test );✦ Anonymous Functions: var test = function(){};✦ setTimeout(function(){ alert( “1 second later” ); }, 1000);
  9. 9. Function Definition✦ Defining a function makes it omni- present, within its scope✦ function test() { return foo(); // Will never be reached, but that’s ok function foo(){ return 1; } }
  10. 10. Functions as Objects✦ Functions can have properties✦ function test(){} test.a = 1; test.b = 2;
  11. 11. Self-Memoization✦ function isPrime( num ) { if ( isPrime.answers[ num ] != null ) return isPrime.answers[ num ]; var prime = num != 1; for ( var i = 2; i < num; i++ ) if ( num % i == 0 ) { prime = false; break; } return isPrime.answers[ num ] = prime; } isPrime.answers = {};✦ isPrime(5) == true
  12. 12. Function Context✦ ‘this’ within a function✦ var obj = { fn: function(){ return this == obj; } }; obj.fn() == true✦ function test(){ return this == window; }
  13. 13. Modify Context✦ [0,1,2].join(“ “) == “0 1 2”✦ [].join.call([0,1,2],” “) == “0 1 2”✦ [].join.call("test"," ") == “t e s t”✦ [].join.apply("test", [" "]) == “t e s t”✦ var str = “test”;✦ str.length str[0] == “t”
  14. 14. Instantiation✦ No ‘classes’ in JavaScript✦ You can instantiate a function✦ function User( name ){ this.name = name; } var user = new User( “John” ); user.name == “John”;✦ User(“John”) name == “John”
  15. 15. Function Prototypes✦ All functions have a prototype property✦ All prototype properties are added to function instances✦ function User(){} var u = new User(); User.prototype.setName = function(name){ this.name = name; }; u.setName(“John”); u.name == “John”;
  16. 16. Inheritance✦ Use the prototype to chain functions together✦ function People(){} People.prototype.human = true; function Resig(name){ this.firstName = name; } Resig.prototype = new People(); Resig.prototype.lastName = “Resig”; var john = new Resig(“John”);
  17. 17. instanceof✦ var john = new Resig(“John”); john instanceof Resig john instanceof Person john instanceof Object✦ All functions have a base prototype of Object
  18. 18. Native Prototypes✦ You can extend the prototypes of native functions✦ String.prototype.join = function(array){ return array.join(this); }; “,”.join([0, 1, 2]) == “0,1,2”✦ Properties are added to all obects of the type✦ Extending Object.prototype is really bad (can’t loop over properties safely, anymore)
  19. 19. ✦ Object.prototype.keys = function(){ var a = []; for ( var i in this ) a.push( i ); return a; }; {a: 1, b: 2].keys().length == 3
  20. 20. Closures✦ Referencing an external variable encapsulates it for later access✦ function Ninja(){ var slices = 0; this.getSlices = function(){ return slices; }; this.slice = function(){ slices++; }; } var ninja = new Ninja(); ninja.slice(); ninja.getSlices() == 1 ninja.slices // doesn’t exist
  21. 21. Currying✦ Pre-fill in arguments to a function, generating a new function✦ Function.prototype.curry = function() { var fn = this, args = Array.prototype.slice.call(arguments); return function() { return fn.apply(this, args.concat( Array.prototype.slice.call(arguments))); }; }; String.prototype.csv = String.prototype.split.curry(/,s*/); var results = ("John, Resig, Boston").csv(); results[1] == "Resig"
  22. 22. DOM
  23. 23. DOM Difficulty✦ JavaScript programming can be hard ✦ Problem isn’t the JavaScript language ✦ Cross-browser issues are frustrating ✦ DOM can be clunky✦ DOM is an object representation of an XML structure (in most cases, an HTML document)
  24. 24. DOM Methods✦ <div></div> document.getElementsByTagName(“div”)✦ <div id=”test”></div> document.getElementById(“test”)✦ removeChild()✦ appendChild() insertBefore()
  25. 25. JavaScript Libraries✦ Come to the rescue!✦ Drastically simplify DOM, Ajax, Animations✦ Use a library, like jQuery!
  26. 26. jQuery
  27. 27. What is jQuery?✦ An open source JavaScript library that simplifies the interaction between HTML and JavaScript.
  28. 28. Ideal for Prototyping✦ Completely unobtrusive✦ Uses CSS to layer functionality✦ Easy to separate behavior✦ Quick, terse, syntax
  29. 29. The Focus of jQueryFind Some Elements Do something with them { { $(“div”).addClass(“special”); jQuery Object
  30. 30. The jQuery Object✦ Commonly named ‘$’✦ Also named ‘jQuery’✦ Completely valid: ✦ jQuery(“div”).addClass(“special”);
  31. 31. Find Some Elements...✦ Full CSS Selector 1-3 Support✦ Basic XPath✦ Better CSS Selector support than most browsers
  32. 32. $(“div”)<div id=”body”> <h2>Some Header</h2> <div class=”contents”> <p>...</p> <p>...</p> </div></div>
  33. 33. $(“#body”)<div id=”body”> <h2>Some Header</h2> <div class=”contents”> <p>...</p> <p>...</p> </div></div>
  34. 34. $(“div#body”)<div id=”body”> <h2>Some Header</h2> <div class=”contents”> <p>...</p> <p>...</p> </div></div>
  35. 35. $(“div.contents p”) <div id=”body”> <h2>Some Header</h2> <div class=”contents”> <p>...</p> <p>...</p> </div> </div>
  36. 36. $(“div > div”)<div id=”body”> <h2>Some Header</h2> <div class=”contents”> <p>...</p> <p>...</p> </div></div>
  37. 37. $(“div:has(div)”) <div id=”body”> <h2>Some Header</h2> <div class=”contents”> <p>...</p> <p>...</p> </div> </div>
  38. 38. Do something with them✦ DOM Manipulation (append, prepend, remove)✦ Events (click, hover, toggle)✦ Effects (hide, show, slideDown, fadeOut)✦ AJAX (load, get, post)
  39. 39. DOM Manipulation✦ $(“a[target]”) .append(“ (Opens in New Window)”);✦ $(“#body”).css({ border: “1px solid green”, height: “40px” });
  40. 40. Events✦ $(“form”).submit(function(){ if ( $(“input#name”).val() == “” ) $(“span.help”).show(); });✦ $(“a#open”).click(function(){ $(“#menu”).show(); return false; });
  41. 41. Animations✦ $(“#menu”).slideDown(“slow”);✦ Individual properties: $(“div”).animate({ fontWeight: “2em”, width: “+=20%”, color: “green” // via plugin });✦ Callbacks: $(“div”).hide(500, function(){ // $(this) is an individual <div> element $(this).show(500); });
  42. 42. Ajax✦ $(“#body”).load(“sample.html div > h1”); ✦ Before: <div id=”body”></div> ✦ After: <div id=”body”> <h1>Hello, world!</h1> </div>✦ $.getJSON(“test.json”, function(js){ for ( var name in js ) $(“ul”).append(“<li>” + name + “</li>”); });
  43. 43. Chaining✦ You can have multiple actions against a single set of elements✦ $(“div”).hide();✦ $(“div”).hide().css(“color”,”blue”);✦ $(“div”).hide().css(“color”,”blue”).slideDown();
  44. 44. Chaining (cont.)✦ $(“ul.open”) // [ ul, ul, ul ] .children(“li”) // [ li, li, li ] .addClass(“open”) // [ li, li, li] .end() // [ ul, ul, ul ] .find(“a”) // [ a, a, a ] .click(function(){ $(this).next().toggle(); return false; }) // [ a, a, a ] .end(); // [ ul, ul, ul ]
  45. 45. Questions? http://ejohn.org/ http://jquery.com/
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×