jquery-day-1.ppt

Embed Size (px)

Citation preview

  • 8/12/2019 jquery-day-1.ppt

    1/136

    Front-end Masters

    day 1pres.learningjquery.com/femasters/

  • 8/12/2019 jquery-day-1.ppt

    2/136

    Outline Philosophy of jQuery and API Walkthrough Dev Tools

    Bare-bones JavaScript

    jQuery Selectors and Traversing

  • 8/12/2019 jquery-day-1.ppt

    3/136

    DOM Scripting

  • 8/12/2019 jquery-day-1.ppt

    4/136

    DOM ScriptingBased on web standards

    Tests features, not browsers

    Unobtrusive

  • 8/12/2019 jquery-day-1.ppt

    5/136

    DOM Scripting

    Books

    Jeremy Keith Peter-Paul Koch Jonathan Snook

    domscripting.com quirksmode.org snook.ca

  • 8/12/2019 jquery-day-1.ppt

    6/136

    Unobtrusive

    custom.js

    Behavior Content

    index.html

    Presentation

    style.css

  • 8/12/2019 jquery-day-1.ppt

    7/136

  • 8/12/2019 jquery-day-1.ppt

    8/136

    jQueryInteraction for the Masses

  • 8/12/2019 jquery-day-1.ppt

    9/136

    Just a few of jQuery's

    BenefitsLets you move quickly from beginner toadvanced

    Improves developer efficiency

    Excellent documentation // pats self on back

    Unobtrusive from the ground up

    Reduces browser inconsistencies

    At its core, a simple concept

  • 8/12/2019 jquery-day-1.ppt

    10/136

  • 8/12/2019 jquery-day-1.ppt

    11/136

    Reduces browser

    inconsistenciesExample:Get the height of the viewport

  • 8/12/2019 jquery-day-1.ppt

    12/136

    var x,y;if (self.innerHeight) { // all except Explorer

    x = self.innerWidth;y = self.innerHeight;

    }

    else if (document.documentElement &&document.documentElement.clientHeight) {// Explorer 6 Strict Modex = document.documentElement.clientWidth;y = document.documentElement.clientHeight;

    }else if (document.body) { // other Explorers

    x = document.body.clientWidth;y = document.body.clientHeight;

    }

    DOM Scripting

  • 8/12/2019 jquery-day-1.ppt

    13/136

    var x = $(window).width();var y = $(window).height();

    jQuery

  • 8/12/2019 jquery-day-1.ppt

    14/136

    Documentation &

    SupportAPI: api.jquery.comForum: forum.jquery.com

    IRC: irc.freenode.net, #jquery

    Coming Soon: learn.jquery.com

  • 8/12/2019 jquery-day-1.ppt

    15/136

  • 8/12/2019 jquery-day-1.ppt

    16/136

    Find Something"Select" elements in the document

  • 8/12/2019 jquery-day-1.ppt

    17/136

  • 8/12/2019 jquery-day-1.ppt

    18/136

  • 8/12/2019 jquery-day-1.ppt

    19/136

  • 8/12/2019 jquery-day-1.ppt

    20/136

  • 8/12/2019 jquery-day-1.ppt

    21/136

  • 8/12/2019 jquery-day-1.ppt

    22/136

    Do Something

    1. Let elements "listen" for something to happen

    the document is ready user does something another "listener" acts

    a certain amount of time elapses

  • 8/12/2019 jquery-day-1.ppt

    23/136

    Do Something

    2. and then do something

    a. Manipulate elements

    b. Animate elements

    c. Communicate with the server

  • 8/12/2019 jquery-day-1.ppt

    24/136

    Dev Tools

  • 8/12/2019 jquery-day-1.ppt

    25/136

  • 8/12/2019 jquery-day-1.ppt

    26/136

    Browser Support Modernizr

    http://www.modernizr.com Can I Use?

    http://caniuse.com

    http://www.modernizr.com/http://caniuse.com/http://caniuse.com/http://www.modernizr.com/
  • 8/12/2019 jquery-day-1.ppt

    27/136

    Code Sharing jsfiddle

    http://jsfiddle.net/ jsbin

    http://jsbin.com

    http://jsbin.com/http://jsbin.com/
  • 8/12/2019 jquery-day-1.ppt

    28/136

    TextMate jQuery Bundle:

    http://github.com/kswedberg

    JavaScript Tools Bundle:http://github.com/subtleGradient

    Sublime Text 2 MacVim

    Espresso jQuery Sugar: code.google.com/p/espresso-jquery-sugar

    Text Editors

    Mac OS X

    http://github.com/kswedberghttp://github.com/subtleGradienthttp://github.com/subtleGradienthttp://github.com/kswedberg
  • 8/12/2019 jquery-day-1.ppt

    29/136

    E jQuery Bundle:

    http://github.com/kswedberg

    Eclipse / Aptana Notepad++ Visual Studio

    and so on.

    Text Editors

    Windows

    http://github.com/kswedberghttp://github.com/kswedberg
  • 8/12/2019 jquery-day-1.ppt

    30/136

    Console DOM Viewer JavaScript debugger Net view Lots of extensions

    http://getfirebug.com/wiki/index.php/Firebug_Extensions

    Firefox: Firebug

    Chrome Developer

    http://getfirebug.com/wiki/index.php/Firebug_Extensionshttp://getfirebug.com/wiki/index.php/Firebug_Extensions
  • 8/12/2019 jquery-day-1.ppt

    31/136

    Chrome Developer

    Tools In many ways, leapfrogging Firebug Live debugging, code changing Lots of "hidden" goodies

    http://code.google.com/chrome/devtools/ Paul Irish screencast: http://youtu.be/nOEw9iiopwI

    Safari: Developer

    http://code.google.com/chrome/devtools/http://www.youtube.com/watch?v=nOEw9iiopwIhttp://www.youtube.com/watch?v=nOEw9iiopwIhttp://code.google.com/chrome/devtools/
  • 8/12/2019 jquery-day-1.ppt

    32/136

    Included since Safari 3.1 Similar to Chrome Dev Tools, but not as advanced Activate via Preferences > Advanced

    Safari: Developer

    Menu

    Internet Explorer 8+:

  • 8/12/2019 jquery-day-1.ppt

    33/136

    Much, much better than in previous versions. Finally includes a console.

    Internet Explorer 8+:

    Developer Tools

  • 8/12/2019 jquery-day-1.ppt

    34/136

    CompanionJS:tinyurl.com/companionjs

    IETester:tinyurl.com/dbtester

    MS Developer Toolbar:tinyurl.com/msdevtoolbar

    Script Debugger:tinyurl.com/msscriptdebug

    None of them comes even close to the tools available inother browsers

    Internet Explorer

  • 8/12/2019 jquery-day-1.ppt

    35/136

    Bare-bones

    JavaScript

  • 8/12/2019 jquery-day-1.ppt

    36/136

    The Basics

    Strings: textual content. wrapped in quotation marks(single or double).

    'hello, my name is Karl' "hello, my name is Karl"

    Numbers: integer (2) or floating point (2.4) or octal (012)or hexadecimal (0xff) or exponent literal (1e+2)

    Booleans: true or false

    In JavaScript, you can work with the following things:

  • 8/12/2019 jquery-day-1.ppt

    37/136

    The Basics

    Arrays: simple lists. indexedstarting with 0

    ['Karl', 'Sara', 'Ben', 'Lucia'] ['Karl', 2, 55] [ ['Karl', 'Sara'], ['Ben', 'Lucia']]

    Objects: lists of key, value pairs {firstName: 'Karl', lastName: 'Swedberg'} {parents: ['Karl', 'Sara'], kids: ['Ben', 'Lucia']}

    In JavaScript, you can work with the following things:

  • 8/12/2019 jquery-day-1.ppt

    38/136

  • 8/12/2019 jquery-day-1.ppt

    39/136

  • 8/12/2019 jquery-day-1.ppt

    40/136

    Loops

    Loops iteratethrough a list of some kind. A common pattern in JavaScript is to build a list, or

    collection, and then do something with each item in that

    list.

  • 8/12/2019 jquery-day-1.ppt

    41/136

    Loops CSS uses implicititeration.

    div { color: red; } /* applies to ALL divs */ JavaScript relies on explicit iteration. Must explicitly loop

    through each div

    jQuery allows for both (because it does the looping foryou)

  • 8/12/2019 jquery-day-1.ppt

    42/136

    Loops

    The two most common loops... forloops for general-purpose iteration. Used with

    arrays or array-like objects)

    for-inloops used with arrays or objects (but don'tuse with arrays)

    The other two are... whileloops do-whileloops

  • 8/12/2019 jquery-day-1.ppt

    43/136

    for (initial value; condition; increment) {// code block

    }

    for Loops three statements and a code block1. initial value

    2. condition

    3. increment

  • 8/12/2019 jquery-day-1.ppt

    44/136

    for Loopsfor(vari=0; i

  • 8/12/2019 jquery-day-1.ppt

    45/136

    for Loopsvardivs =document.getElementsByTagName('div');

    for(vari =0; i

  • 8/12/2019 jquery-day-1.ppt

    46/136

    for Loopsvardivs =document.getElementsByTagName('div');

    // better to store length in variable firstvardivCount =divs.length

    for(vari =0; i

  • 8/12/2019 jquery-day-1.ppt

    47/136

    for Loopsvardivs =document.getElementsByTagName('div');

    // can store it directly in the initializerfor(vari=0, divCount=divs.length; i

  • 8/12/2019 jquery-day-1.ppt

    48/136

    for-in Loopsvarfamily={dad: 'Karl',mom: 'Sara',son: 'Benjamin',daughter: 'Lucia'

    }

    for(varpersoninfamily) {alert('The '+person +' is '+family[person]);

    }

    This is your variable,

    so it can be anything!

    hil d d hil

  • 8/12/2019 jquery-day-1.ppt

    49/136

    while and do-whilevari =1;while(i

  • 8/12/2019 jquery-day-1.ppt

    50/136

    Functions

    Th B i F ti

  • 8/12/2019 jquery-day-1.ppt

    51/136

    The Basics: Functions

    Functions allow you to definea block of code, name that block,and then callit later as many times as you want.

    functionmyFunction( ) { /* code goes here */} // defining myFunction( ) // calling the function myFunction

    You can define functions with parameters function myFunction(param1, param2) { /* code goes here */

    }

    You can call functions with arguments: myFunction('one', 'two')

    In JavaScript, you can also work with functions:

    F ti

  • 8/12/2019 jquery-day-1.ppt

    52/136

    Functions// define a functionfunctiondoSomething() {alert('I am something');

    }

    // call the functiondoSomething();

    F ti

  • 8/12/2019 jquery-day-1.ppt

    53/136

    Functions// define a functionfunctionsumThing(a, b) {returna +b;

    }

    // call the functionalert( sumThing(1, 2) );

    F ti

  • 8/12/2019 jquery-day-1.ppt

    54/136

    Functions// define a functionfunctionsumThing(a, b) {returna +b;

    }

    varmySum =sumThing(1, 2);// call the functionalert( mySum );

    Th t Obj t

  • 8/12/2019 jquery-day-1.ppt

    55/136

    The arguments Object Every function has an arguments object

    a collection of the arguments passed to the functionwhen it is called

    an "array-like object" in that it is indexed and has alengthproperty but can't attach array methods to it can be looped through allows for variable number of arguments

    Functions

  • 8/12/2019 jquery-day-1.ppt

    56/136

    Functions// call the function

    functionlogThing() {

    for(vari=0; i > 1

    >> 2

    >> three

    */

    Exercise

  • 8/12/2019 jquery-day-1.ppt

    57/136

    Exercise

    Convert the sumThing function to allow for variablenumber of arguments.

    functionsumThing(a, b) {returna +b;

    }Use a forloop to loop through the argumentsobject,adding to a "sum" variable with each iteration.

    After the loop, return sum.

    (Simple) Solution

  • 8/12/2019 jquery-day-1.ppt

    58/136

    (Simple) Solution// define a functionfunctionsumThing() {

    varsum =0,countArgs =arguments.length;

    for(vari =0; i

  • 8/12/2019 jquery-day-1.ppt

    59/136

    functionmultiple(n) {

    functionf(x) {

    returnx*n;

    }

    returnf;}

    vartriple=multiple(3);

    varquadruple=multiple(4);

    console.log( triple(5) );// 15console.log( quadruple(5) );// 20

    console.log( multiple(4)(5) );// 20

    Returning Functions Functions can return other functions

    ame vs.Anonymous

  • 8/12/2019 jquery-day-1.ppt

    60/136

    Anonymous

    Functions Named: function foo() { } // function declaration var foo = function foo() { }; // function expression

    Anonymous: var foo = function() { }; // function expression

    Anonymous Functions

  • 8/12/2019 jquery-day-1.ppt

    61/136

    Anonymous Functions Prevalent in jQuery Good for creating closures Used as "callback" functions

    Can be used as object properties (methods)

    lets take a look ...

    Anonymous Functions

  • 8/12/2019 jquery-day-1.ppt

    62/136

    $(document).ready(function() {

    });

    Anonymous Functions Prevalent in jQuery

    Anonymous Functions

  • 8/12/2019 jquery-day-1.ppt

    63/136

    function() {

    // variables are defined within this scope// avoid name collisions

    }

    Anonymous Functions Good for creating closures

    Anonymous Functions

  • 8/12/2019 jquery-day-1.ppt

    64/136

    (function() {// variables are defined within this scope// avoid name collisions

    })();

    Anonymous Functions Good for creating closures Can be definedand then immediately invoked:

    immediately invoked function expression, ( a.k.a. IIFE;pronounced iffy)

    Anonymous Functions

  • 8/12/2019 jquery-day-1.ppt

    65/136

    (function($) { // "$" is the function's param

    })(jQuery); // function is calledwith "jQuery"

    Anonymous Functions Good for creating closures Used by plugins to keep jQuery safe.

  • 8/12/2019 jquery-day-1.ppt

    66/136

  • 8/12/2019 jquery-day-1.ppt

    67/136

    Objects

    Objects

  • 8/12/2019 jquery-day-1.ppt

    68/136

    Objects

    Objects are objects : { } Arrays are objects : [ ] even Functions are objects : function( ) { } jQuery is an object Numbers, strings, and booleans (true/false) are primitive

    data types, but they have object wrappers.

    In JavaScript, everything is an object. Well, almost everything.

    Global Object

  • 8/12/2019 jquery-day-1.ppt

    69/136

    Global Object

    location

    parseInt(); parseFloat() isNaN() encodeURI(); decodeURI()

    setTimeout(); clearTimeout() setInterval(); clearInterval()

    In the browser environment, the global object is windowIt collects all functions and variables that are global in scope.Usually implied.

    Comes with some useful properties and methods:

    Date Object

  • 8/12/2019 jquery-day-1.ppt

    70/136

    Date Object

    varnow=newDate();// current date and time

    varthen=newDate('08/12/2000 14:00');

    console.log( then.getTime() );// 966103200000

    console.log( then.toString() );

    // Sat Aug 12 2000 14:00:00 GMT-0400 (EDT)

    console.log( then.getMonth() );// 7!!!!

    RegExp Object

  • 8/12/2019 jquery-day-1.ppt

    71/136

    Regular Expression

    Object constructor varre=newRegExp('hello');

    Regular expression literal varre=/hello/;

  • 8/12/2019 jquery-day-1.ppt

    72/136

  • 8/12/2019 jquery-day-1.ppt

    73/136

    RegExp Syntax

  • 8/12/2019 jquery-day-1.ppt

    74/136

    RegExp Syntax

    Most characters (incl. all alphanumerics) representthemselves

    Special characters can be escaped with a backslash (\)

    Character Classes

  • 8/12/2019 jquery-day-1.ppt

    75/136

    Character Classes

    /t.p/matches 'tap' and 'tip' and 'top' /t[ai]p/matches 'tap' and 'tip', not 'top' /t[a-k]p/ matches 'tap' and 'tip', not 'top'

    /t[^m-z]p/matches 'tap' and 'tip', not 'top'

    Repetition

  • 8/12/2019 jquery-day-1.ppt

    76/136

    Repetition

    /frog*/ matches'fro', 'frog', 'frogg', ... /frog+/ matches'frog','frogg', ... /frog?/ matches'fro' or'frog'

    /frog{2,3}/ matches'frogg' or'froggg'

    Grouping

  • 8/12/2019 jquery-day-1.ppt

    77/136

    Grouping

    Grouping /(frog)*/matches "frog" or "frogfrog"

    Alternation

    /th(is|at)/matches "this" and "that"

    Anchor Points

  • 8/12/2019 jquery-day-1.ppt

    78/136

    c o o s

    ^matches the beginning of a string $matches the end of a string \bmatches word boundaries

    Exercises

  • 8/12/2019 jquery-day-1.ppt

    79/136

    Write a regular expression that matches any word thatstarts with a vowel.

    Write a regular expression that matches any HTML tag.

    String RegExpM th d

  • 8/12/2019 jquery-day-1.ppt

    80/136

    Methods str.search(re) str.match(re)

    str.replace(re, replacement)

    str.split(re)

    String Replacement

  • 8/12/2019 jquery-day-1.ppt

    81/136

    g pvarstr=

    'The quick brown fox jumps over the lazy dog.';

    console.log(str.replace(/[aeiou]/, '*'));

    // Th* quick brown fox jumps over the lazy dog.

    RegExp Flags

  • 8/12/2019 jquery-day-1.ppt

    82/136

    g p g

    Placed after closing /character Global (g): find as many as possible Case insensitive (i)

    Multiline (m): ^and $work with newlines

    String Replacement

  • 8/12/2019 jquery-day-1.ppt

    83/136

    g pvarstr=

    'The quick brown fox jumps over the lazy dog.';

    console.log(str.replace(/[aeiou]/g, '*'));

    // Th* q**ck br*wn f*x j*mps *v*r th* l*zy d*g.

    console.log(str.replace(/the/gi, 'a'));

    // a quick brown fox jumps over a lazy dog.

    Backreferences

  • 8/12/2019 jquery-day-1.ppt

    84/136

    varstr='The quick brown fox jumps over the lazy dog.';

    console.log(str.replace(/r(.)/g, '$1x'));

    // The quick boxwn fox jumps ove xthe lazy dog.

    ReplacementFunctions

  • 8/12/2019 jquery-day-1.ppt

    85/136

    Functionsvarstr='Kill 5+9 birds with 2+5 stones.';functionadd(match, first, second) {returnparseInt(first, 10) +parseInt(second, 10);

    }str=str.replace(/([0-9]+)\+([0-9]+)/g, add);console.log(str);// Kill 14 birds with 7 stones.

    Exercises

  • 8/12/2019 jquery-day-1.ppt

    86/136

    Write a function that uppercases all the vowels ina string.

    Write a function that strips the angle brackets

    from around any HTML tags in a string.

    Greediness

  • 8/12/2019 jquery-day-1.ppt

    87/136

    Repeat operators usually match as much of the string aspossible; they are greedy

    JavaScript supports reluctantrepetition as well Append ?to the repeat operator

    And Much More

  • 8/12/2019 jquery-day-1.ppt

    88/136

    JavaScript supports most Perl regular expressionextensions

    POSIX character classes Unicode character escapes Look-ahead assertions

    Math Object

  • 8/12/2019 jquery-day-1.ppt

    89/136

    Not a constructor, a singleton Gathers useful methods and properties Math.PI

    Math.abs(), Math.sin(), Math.pow(), Math.random(), Math.max(), Math.min() Math.round(), Math.floor(), Math.ceil()

  • 8/12/2019 jquery-day-1.ppt

    90/136

    Object Literals

  • 8/12/2019 jquery-day-1.ppt

    91/136

    varperson ={

    firstName: 'Karl',lastName: 'Swedberg',hello: function() {return'Hello, my name is '+

    this.firstName +' '+this.lastName;}

    };

    personis the object firstNameand lastNameare properties hellois a method(a property that is a function)

    Object Literals

  • 8/12/2019 jquery-day-1.ppt

    92/136

    varperson ={firstName: 'Karl',lastName: 'Swedberg',hello: function() {return'Hello, my name is '+

    this.firstName +' '+this.lastName;},interests: {athletic: ['racquetball', 'karate', 'running'],musical: ['rock', 'folk', 'jazz', 'classical']

    }

    };

    interestsis a propertyand

    an object

    Object Literals

  • 8/12/2019 jquery-day-1.ppt

    93/136

    var person = {firstName:'Karl',lastName:'Swedberg',hello:function() {

    return 'Hello, my name is ' +

    this.firstName + ' ' + this.lastName;} // notice, no comma here!

    };

    Object Literalsdot notation

  • 8/12/2019 jquery-day-1.ppt

    94/136

    dot notation

    var person = {firstName: 'Karl',lastName: 'Swedberg',hello: function() {

    return 'Hello, my name is ' +

    this.firstName + ' ' + this.lastName;}

    };

    // "dot" notationperson.firstName; // 'Karl'person.lastName; // 'Swedberg'person.hello() // 'Hello, my name is Karl Swedberg'

    Object Literalsarray notation

  • 8/12/2019 jquery-day-1.ppt

    95/136

    array notation

    var person = {firstName: 'Karl',lastName: 'Swedberg',hello: function() {

    return 'Hello, my name is ' +

    this.firstName + ' ' + this.lastName;}

    };

    // array notationperson['firstName']; // 'Karl'person['lastName']; // 'Swedberg'person['hello']() // 'Hello, my name is Karl Swedberg'

    Object Literals

  • 8/12/2019 jquery-day-1.ppt

    96/136

    varperson ={

    firstName: 'Karl',lastName: 'Swedberg',hello: function() {return'Hello, my name is '+

    this.firstName +' '+this.lastName;},

    interests: {athletic: ['racquetball', 'karate', 'running'],musical: ['rock', 'folk', 'jazz', 'classical']

    }};// person['interests']['musical'][1] == ??

    // == person.interests.musical[1]

    Object Literalsvar person = {

  • 8/12/2019 jquery-day-1.ppt

    97/136

    varperson ={

    firstName: 'Karl',lastName: 'Swedberg',hello: function() {return'Hello, my name is '+

    this.firstName +' '+this.lastName;}

    };person.firstName='Karl';

    varprop ='firstName';person[ prop ];// 'Karl'

    prop ='lastName';person[ prop ];// 'Swedberg'

    Object Literalsvarblah;

  • 8/12/2019 jquery-day-1.ppt

    98/136

    ;varperson={

    firstName:'Karl',lastName:'Swedberg',hello: function() {return'Hello, my name is '+

    this.firstName+' '+this.lastName;}

    };

    for(varelinperson) {blah=typeofperson[el] =='function'?

    person[el]() :person[el];

    console.log( blah);}

    Object Literals

  • 8/12/2019 jquery-day-1.ppt

    99/136

    doSomething({

    speed: 'fast',height: 500,width: 200,somethingElse: 'yes'

    });

    doSomething({width: 300});

    Great as function arguments single argument allows flexibility when calling the function

    JSONJavaScript Object Notation

  • 8/12/2019 jquery-day-1.ppt

    100/136

    a data interchangeformat. In other words, a format forpassing data back and forth discovered and popularized by Douglas Crockford a subsetof JavaScript Object Literal Notation

    a tree-like structure of object(s) and/or array(s) no functions all strings, including object keys, take double quotes

    JSON

  • 8/12/2019 jquery-day-1.ppt

    101/136

    {"firstName": "Karl",

    "lastName": "Swedberg",

    "age": 24,

    "interests": {

    "athletic": ["racquetball",

    "karate"

    ]

    }

    }

    JSON

  • 8/12/2019 jquery-day-1.ppt

    102/136

    {"firstName":"Karl","lastName":"Swedberg","age":24,"interests":{"athletic":["racq

    uetball","karate"]}}

  • 8/12/2019 jquery-day-1.ppt

    103/136

    Referencing Scriptsin the HTML

    browser slides

  • 8/12/2019 jquery-day-1.ppt

    104/136

    Selectors &

    Traversal

    At the heart ofjQuery...

  • 8/12/2019 jquery-day-1.ppt

    105/136

    jQ y Find something Do something

    CSS Selectors

  • 8/12/2019 jquery-day-1.ppt

    106/136

    element {} #id {} .class {} selector1, selector2{} ancestor descendant{} parent > child{}

    :nth-child() {}

    CSS Selectors(jQuery Equivalents)

  • 8/12/2019 jquery-day-1.ppt

    107/136

    $('element') $('#id') $('.class') $('selector1, selector2') $('ancestor descendant') $('parent > child')

    $(':nth-child(n)')

    (j y q )

    CSS Selectors(jQuery Equivalents)

  • 8/12/2019 jquery-day-1.ppt

    108/136

    $('element') $('#id') $('.class') $('selector1, selector2') $('ancestor descendant') $('parent > child')

    $(':nth-child(n)')

    and others $('prev + selector') $('prevAll ~

    selector')$(':nth-child(an+b')$(':not(selector)')

    $(':checked')

    $(':disabled')

    CSS AttributeSelectors

  • 8/12/2019 jquery-day-1.ppt

    109/136

    $('input[name=firstname\\[\\]]') $('[title]') has the attribute $('[attr="val"]') attr equals val

    $('[attr!="val"]') attr does not equal val $('[attr~="val"]') attr has val as one of space-sep.vals

    $('[attr ="val"]') attr begins with val

    $('[attr$="val"]') attr ends with val $('[attr*="val"]') attr has val anywhere within

    Custom FormSelectors

  • 8/12/2019 jquery-day-1.ppt

    110/136

    $('div.myclass :checkbox') $(':input') , , ,

    $(':text') $(':radio') $(':button') , $(':selected')

    etc.

    Custom Misc.Selectors

  • 8/12/2019 jquery-day-1.ppt

    111/136

    $(':animated') $(':has(descendant)') $(':eq(n)')

    $(':lt(n)') $(':gt(n)') $(':even') $(':odd')

    $(':visible')$(':hidden')$(':header')$(':contains(string)')

    Selectors

  • 8/12/2019 jquery-day-1.ppt

    112/136

    List of all selectors on the jQuery API site http://api.jquery.com/category/selectors

    http://api.jquery.com/category/selectorshttp://api.jquery.com/category/selectors
  • 8/12/2019 jquery-day-1.ppt

    113/136

    Move Up parent() : up one level $('li.bottom').parent(); parents() : up multiple levels $('span').parents('ul');

  • 8/12/2019 jquery-day-1.ppt

    114/136

    level 1 level 2 level 3

    parents() : up multiple levels $( span ).parents( ul );

    parentsUntil() : possibly multiple $('span').parentsUntil('ul');

    Move Up .closest(selector) : up 0 or more levels

  • 8/12/2019 jquery-day-1.ppt

    115/136

    level 1 level 2 level 3

    ( ) p

    $('span').closest('ul'); $('.bottom').closest('li');

    Move Sideways

  • 8/12/2019 jquery-day-1.ppt

    116/136

    .siblings() .next() .nextAll()

    .nextUntil()

    .prev() .prevAll() .prevUntil()

    Move Down

  • 8/12/2019 jquery-day-1.ppt

    117/136

    .children() .find()

    Filter

  • 8/12/2019 jquery-day-1.ppt

    118/136

    .filter(selector) .filter('.some-class') .filter(function)

    .filter(function() {

    return$(this).parents('li').length>=2; });

    Filter

  • 8/12/2019 jquery-day-1.ppt

    119/136

    .not(selector) .not('.some-class') .not(function)

    .not(function() {

    return$(this).parents('li').length>=2; });

    Filter

  • 8/12/2019 jquery-day-1.ppt

    120/136

    .slice() .slice(2) .slice(-2)

    .slice(3,6)

    .slice(2,-1) .eq()

    .eq(2)

    .eq(-2)

  • 8/12/2019 jquery-day-1.ppt

    121/136

    Check

  • 8/12/2019 jquery-day-1.ppt

    122/136

    .hasClass(class) .is(selector)

    ** returns a boolean

    Traversal Methods

  • 8/12/2019 jquery-day-1.ppt

    123/136

    List of all traversal methods on the jQuery API site http://api.jquery.com/category/traversing

    Chaining

    S

    http://api.jquery.com/category/traversinghttp://api.jquery.com/category/traversing
  • 8/12/2019 jquery-day-1.ppt

    124/136

    JavaScript has chaining built in. 'swap this text'.replace(/w/, 'n').replace(/this/,'that'); '616-555-1212'.split('-').join('.');

    jQuery takes advantage of this concept by having almostall methods return the jQuery object.

    Chaining

    Ch i t l th d t th

  • 8/12/2019 jquery-day-1.ppt

    125/136

    $('a').parent('li').siblings().find('a')

    Chain traversal methods together

    Chaining

    Att h lti l b h i

  • 8/12/2019 jquery-day-1.ppt

    126/136

    $('a').removeClass('old').addClass('new');

    Attach multiple behaviors.

    Chaining

    DOM T l th d diff t f th jQ

  • 8/12/2019 jquery-day-1.ppt

    127/136

    $('a').addClass('foo').parent('li').removeClass('foo')

    DOM Traversal methods are different from other jQuerychaining methods! New jQuery instance is created with each one.

    Chaining

    Ja aScript ignores hite space so se it to o r ad antage

  • 8/12/2019 jquery-day-1.ppt

    128/136

    var lis = $('.containerli:first').addClass('first-li').next()

    .addClass('second-li').end()

    .nextAll()

    .addClass('not-first-li').end();// unnecessary; added for symmetry

    JavaScript ignores white space, so use it to your advantage.

    Looping

    Implicit Iteration

  • 8/12/2019 jquery-day-1.ppt

    129/136

    $('li').removeClass('myclass'); //implicit

    $('li').each(function(index) { //explicit$(this).append( ' #'+(index+1) );});

    Implicit Iteration Explicit Iteration (Looping)

    this Keyword

  • 8/12/2019 jquery-day-1.ppt

    130/136

    $('li').each(function() {console.log( this);// DOM elementconsole.log( $(this) );

    });

    Refers to the current object jQuery sets thisto matched elements in the jQuery object.

    Tips

    Store selectors used more than once in variables

  • 8/12/2019 jquery-day-1.ppt

    131/136

    var$listItems =$('li');varnumItems =$listItems.length

    //no need for length check$listItems.addClass('pretty');

    if(numItems) {// do something with other elements}

    Store selectors used more than once in variables Use length property to check existence

    ...but often no need for the check

    Tips

    Concatenate to pass in a variable

  • 8/12/2019 jquery-day-1.ppt

    132/136

    $('#menuli').each(function(index) {$(this).click(function() {

    $('#footer li:eq('+ index +')').addClass('active');});

    });

    Concatenate to pass in a variable

  • 8/12/2019 jquery-day-1.ppt

    133/136

  • 8/12/2019 jquery-day-1.ppt

    134/136

    Tips

    Avoid jQuery's custom selectors when possible

  • 8/12/2019 jquery-day-1.ppt

    135/136

    // slower$('li:eq(3)')$('li:lt(3)')

    // faster$('li').eq(3)$('li').slice(0, 3)

    Avoid jQuery s custom selectors when possible

  • 8/12/2019 jquery-day-1.ppt

    136/136

    Q & A