JQuery Tutorial

Transcription

Jquery Tutorial

Outline Philosophy of jQuery and API WalkthroughDev ToolsBare-bones JavaScriptjQuery Selectors and Traversing

DOM Scripting

DOM Scripting Based on web standards Tests features, not browsers Unobtrusive

DOM ScriptingBooksJeremy KeithPeter-Paul KochJonathan Snookdomscripting.comquirksmode.orgsnook.ca

ex.htmlstyle.css

DOMScripting Verboseif (!document.getElementsByTagName) { return false; }var quotes document.getElementsByTagName("blockquote");for (var i 0; i quotes.length; i ) {var source quotes[i].getAttribute("cite");if (source) {var link f",source);var text hild(text);var para document.createElement("p");para.className endChild(para);}}

jQueryInteraction for the Masses

Just a few of jQuery'sBenefits Lets 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

ex.htmlstyle.csscustom.js

Reduces browserinconsistencies Example:Get the height of the viewport

DOM Scriptingvar x,y;if (self.innerHeight) { // all except Explorerx 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 Explorersx document.body.clientWidth;y document.body.clientHeight;}

jQueryvar x (window).width();var y (window).height();

Documentation &Support– API: api.jquery.com– Forum: forum.jquery.com– IRC: irc.freenode.net, #jquery– Coming Soon: learn.jquery.com

Simple Concept Find somethingDo something

Find Something"Select" elements in the document

Do Something

Do Something1. Let elements "listen" for something to happen the document is readyuser does somethinganother "listener" actsa certain amount of time elapses

Do Something2. and then do somethinga. Manipulate elementsb. Animate elementsc. Communicate with the server

Dev Tools

Dev Tools up to five browsers to test against FirefoxChromeInternet ExplorerSafariOperadeveloper tools can make your life much easier

Browser Support Modernizr http://www.modernizr.comCan I Use? http://caniuse.com

Code Sharing jsfiddle http://jsfiddle.net/jsbin http://jsbin.com

Text Editors TextMate Mac OS XjQuery Bundle:http://github.com/kswedbergJavaScript Tools Bundle:http://github.com/subtleGradientSublime Text 2MacVimEspresso jQuery Sugar:code.google.com/p/espresso-jquery-sugar

Text EditorsWindows E jQuery Bundle:http://github.com/kswedbergEclipse / AptanaNotepad Visual Studioand so on.

Firefox: Firebug ConsoleDOM ViewerJavaScript debuggerNet viewLots of ebug Extensions

Chrome DeveloperToolsIn many ways, leapfrogging FirebugLive debugging, code changingLots of "hidden" goodieshttp://code.google.com/chrome/devtools/Paul Irish screencast: http://youtu.be/nOEw9iiopwI

Safari: DeveloperMenuIncluded since Safari 3.1Similar to Chrome Dev Tools, but not as advancedActivate via Preferences Advanced

Internet Explorer 8 :Developer Tools Much, much better than in previous versions.Finally includes a console.

Internet Explorer 7 l.com/dbtesterMS Developer Toolbar:tinyurl.com/msdevtoolbarScript Debugger:tinyurl.com/msscriptdebugNone of them comes even close to the tools available inother browsers

Bare-bonesJavaScript

The BasicsIn JavaScript, you can work with the following things: 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

The BasicsIn JavaScript, you can work with the following things: Arrays: simple lists. indexed starting 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']}

Variables Always declare your variables!If you don't, they will be placed in the global scope(more about that later). bad: myName 'Karl';good: var myName 'Karl';still good: var myName 'Karl';// more stuffmyName 'Joe';

Conditionals andOperators conditionals: if, elseswitchoperators: , -, *, %, , - , , , ! , , , , ! !, &&,

Loops Loops iterate through a list of some kind.A common pattern in JavaScript is to build a list, orcollection, and then do something with each item in thatlist.

Loops CSS uses implicit iteration. div { color: red; } /* applies to ALL divs */JavaScript relies on explicit iteration. Must explicitly loopthrough each divjQuery allows for both (because it does the looping foryou)

Loops The two most common loops. for loops — for general-purpose iteration. Used witharrays or array-like objects)for-in loops — used with arrays or objects (but don'tuse with arrays)The other two are. while loopsdo-while loops

for Loops three statements and a code block1. initial value2. condition3. incrementfor (initial value; condition; increment) {// code block}

for Loopsfor (var i 0; i 3; i ) {} alert(i 1);This is your variable,so it can be anything!(but developers oftenuse “i”)

for Loopsvar divs document.getElementsByTagName('div');for (var i 0; i divs.length; i ) {// do something with each div individuallydivs[i].style.color 'red';}

for Loopsvar divs document.getElementsByTagName('div');// better to store length in variable firstvar divCount divs.lengthfor (var i 0; i divCount; i ) {// do something with each div individuallydivs[i].style.color 'red';}

for Loopsvar divs document.getElementsByTagName('div');// can store it directly in the initializerfor (var i 0, divCount divs.length; i divCount; i ) {// do something with each div individuallydivs[i].style.color 'red';}

for-in Loopsvar family {dad: 'Karl',mom: 'Sara',son: 'Benjamin',daughter: 'Lucia'}This is your variable,so it can be anything!for (var person in family) {alert('The ' person ' is ' family[person]);}

while and do-whilevar i 1;while (i 4) {alert(i);i ;}var j 1;// code block always executed at least oncedo {alert(j);j ;} while (j 4)

Functions

The Basics: FunctionsIn JavaScript, you can also work with functions: Functions allow you to define a block of code, name that block,and then call it later as many times as you want. function myFunction( ) { /* code goes here */ } // definingmyFunction( ) // calling the function myFunctionYou can define functions with parameters function myFunction(param1, param2 ) { /* code goes here */}You can call functions with arguments: myFunction('one', 'two')

Functions// define a functionfunction doSomething() {alert('I am something');}// call the functiondoSomething();

Functions// define a functionfunction sumThing(a, b) {return a b;}// call the functionalert( sumThing(1, 2) );

Functions// define a functionfunction sumThing(a, b) {return a b;}var mySum sumThing(1, 2);// call the functionalert( mySum );

The argumentsObjectEvery function has an arguments object a collection of the arguments passed to the functionwhen it is calledan "array-like object" in that it is indexed and has alength property but can't attach array methods to itcan be looped throughallows for variable number of arguments

Functions// call the functionfunction logThing() {for (var i 0; i arguments.length; i ) {console.log(arguments[i]);}}// call the functionlogThing(1, 2, 'three');/* prints to the console: 1 2 three*/

ExerciseConvert the sumThing function to allow for variablenumber of arguments.function sumThing(a, b) {return a b;}Use a for loop to loop through the arguments object,adding to a "sum" variable with each iteration.After the loop, return sum.

(Simple) Solution// define a functionfunction sumThing() {var sum 0,countArgs arguments.length;for (var i 0; i countArgs; i ) {sum arguments[i];}return sum;}// call the functionconsole.log( sumThing(1, 2, 4 ) );

Returning FunctionsFunctions can return other functionsfunction multiple(n) {function f(x) {return x * n;}return f;}var triple multiple(3);var quadruple multiple(4);console.log( triple(5) ); // 15console.log( quadruple(5) ); // 20console.log( multiple(4)(5) ); // 20

Named: Named vs.AnonymousFunctionsfunction foo() { } // function declarationvar foo function foo() { }; // function expressionAnonymous: var foo function() { }; // function expression

Anonymous Functions Prevalent in jQueryGood for creating closuresUsed as "callback" functionsCan be used as object properties (methods)let’s take a look .

Anonymous Functions Prevalent in jQuery (document).ready(function() {});

Anonymous Functions Good for creating closuresfunction() {// variables are defined within this scope// avoid name collisions}

Anonymous Functions Good for creating closuresCan be defined and then immediately invoked:“immediately invoked function expression,” ( a.k.a. IIFE;pronounced “iffy”)(function() {// variables are defined within this scope// avoid name collisions})();

Anonymous Functions Good for creating closuresUsed by plugins to keep jQuery safe.(function( ) { // " " is the function's param})(jQuery); // function is called with "jQuery"

Anonymous Functions Used as "callback" functions ('p').slideDown('slow', function() {// code in here is not executed// until after the slideDown is finished// jQuery calls the code in here when effectends});

Objects

ObjectsIn JavaScript, everything is an object. Well, almost everything. Objects are objects : { }Arrays are objects : [ ]even Functions are objects : function( ) { }jQuery is an objectNumbers, strings, and booleans (true/false) are primitivedata types, but they have object wrappers.

Global ObjectIn 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: locationparseInt(); parseFloat()isNaN()encodeURI(); decodeURI()setTimeout(); clearTimeout()setInterval(); clearInterval()

Date Objectvar now new Date(); // current date and timevar then new Date('08/12/2000 14:00');console.log( then.getTime() ); // 966103200000console.log( then.toString() );// Sat Aug 12 2000 14:00:00 GMT-0400 (EDT)console.log( then.getMonth() ); // 7 !!!!

RegExp ObjectRegular Expression Object constructor var re new RegExp('hello');Regular expression literal var re /hello/;

Creating a RegExp Object constructor var re new RegExp('hello');Regular expression literal var re /hello/;

Using a RegExpvar text 'The quick brown fox';var re new RegExp('quick');console.log( re.test(text) ); // trueconsole.log( /brown/.test(text) ); // trueconsole.log( /red/.test(text) ); // false

RegExp Syntax Most characters (incl. all alphanumerics) representthemselvesSpecial characters can be escaped with a backslash (\)

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 /frog*/ matches 'fro', 'frog', 'frogg', ./frog / matches 'frog', 'frogg', ./frog?/ matches 'fro' or 'frog'/frog{2,3}/ matches 'frogg' or 'froggg'

Grouping Grouping /(frog)*/ matches "frog" or "frogfrog"Alternation /th(is at)/ matches "this" and "that"

Anchor Points matches the beginning of a string matches the end of a string\b matches word boundaries

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

String RegExpMethodsstr.search(re) str.match(re) str.replace(re, replacement) str.split(re)

String Replacementvar str '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 Placed after closing / characterGlobal (g): find as many as possibleCase insensitive (i)Multiline (m): and work with newlines

String Replacementvar str '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.

Backreferencesvar str '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.

ReplacementFunctionsvar str 'Kill 5 9 birds with 2 5 stones.';function add(match, first, second) {return parseInt(first, 10) parseInt(second, 10);}str str.replace(/([0-9] )\ ([0-9] )/g, add);console.log(str);// Kill 14 birds with 7 stones.

ExercisesWrite a function that uppercases all the vowels ina string.Write a function that strips the angle bracketsfrom around any HTML tags in a string.

Greediness Repeat operators usually match as much of the string aspossible; they are greedyJavaScript supports reluctant repetition as well Append ? to the repeat operator

And Much More JavaScript supports most Perl regular expressionextensions POSIX character classesUnicode character escapesLook-ahead assertions

Math Object Not a constructor, a singleton Gathers useful methods and properties Math.PIMath.abs(), Math.sin(), Math.pow(),Math.random(),Math.max(), Math.min()Math.round(), Math.floor(), Math.ceil()

CSS Tip Object literal notation looks a lot like CSS style rulenotation!CSS:h3 {font-size: 1.2em;line-height: 1;}JS:var h3 {fontSize: '1.2em','line-height': 1};

Object Literals person is the objectfirstName and lastName are propertieshello is a method (a property that is a function)var person {firstName: 'Karl',lastName: 'Swedberg',hello: function() {return 'Hello, my name is ' this.firstName ' ' this.lastName;}};

Object Literals interests is a property and an objectvar person {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']}};

Object Literalsvar person {firstName: 'Karl',lastName: 'Swedberg',hello: function() {return 'Hello, my name is ' this.firstName ' ' this.lastName;} // notice, no comma here!};

Object Literals“dot” notationvar 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 notationvar 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 Literalsvar person {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 {firstName: 'Karl',lastName: 'Swedberg',hello: function() {return 'Hello, my name is ' this.firstName ' ' this.lastName;}};person.firstName 'Karl';var prop 'firstName';person[ prop ]; // 'Karl'prop 'lastName';person[ prop ]; // 'Swedberg'

Object Literalsvar blah;var person {firstName: 'Karl',lastName: 'Swedberg',hello: function() {return 'Hello, my name is ' this.firstName ' ' this.lastName;}};for (var el in person) {blah typeof person[el] 'function' ?person[el]() :person[el];console.log( blah );}

Object Literals Great as function argumentssingle argument allows flexibility when calling the functiondoSomething({speed: 'fast',height: 500,width: 200,somethingElse: 'yes'});doSomething({width: 300});

JSONJavaScript Object Notation a data interchange format. In other words, a format forpassing data back and forth“discovered” and popularized by Douglas Crockforda subset of JavaScript Object Literal Notation a tree-like structure of object(s) and/or array(s)no functionsall strings, including object keys, take double quotes

JSON{"firstName": "Karl","lastName": "Swedberg","age": 24,"interests": {"athletic": ["racquetball","karate"]}}

e"]}}

Referencing Scriptsin the HTMLbrowser slides

Selectors &Traversal

At the heart ofjQuery.Find somethingDo something

CSS Selectors element {}#id {}.class {}selector1, selector2 {}ancestor descendant {}parent child {}:nth-child() {}

CSS Selectors(jQuery Equivalents) ('element') ('#id') ('.class') ('selector1, selector2') ('ancestor descendant') ('parent child') (':nth-child(n)')

CSS Selectors(jQuery Equivalents) ('element') ('#id') ('.class') ('selector1, selector2') ('ancestor descendant') ('parent child') (':nth-child(n)') and others ('prev selector') ('prevAll selector') (':nthchild(an b') (':not(selector)') (':checked') (':disabled')

CSS AttributeSelectors ('input[name firstname\\[\\]]') ('[title]')has the attribute ('[attr "val"]')attr equals val ('[attr! "val"]')attr does not equal val ('[attr "val"]')valsattr has val as one of space-sep. ('[attr "val"]')attr begins with val ('[attr "val"]')attr ends with val ('[attr* "val"]')attr has val anywhere within

Custom FormSelectors ('div.myclass :checkbox') (':input') button input , textarea , select , (':text') input type "text" (':radio') input type "radio" (':button') input type "button" , button (':selected') option selected "selected" etc.

Custom Misc.Selectors (':animated') (':has(descendant)') (':eq(n)') (':lt(n)') (':gt(n)') (':even') (':odd') (':visible') (':hidden') (':header') (':contains(string)')

Selectors List of all selectors on the jQuery API sitehttp://api.jquery.com/category/selectors

Traversal Methods Move UpMove SidewaysMove DownFilterContextCheck

Move Upparent() : up one level ('li.bottom').parent();parents() : up multiple levels ('span').parents('ul');parentsUntil() : possibly multiple ul ('span').parentsUntil('ul'); li level 1 ul class "foo" ul 3 /li li level 2 li class "bottom" span level /span /ul /li /ul /li /ul

Move Up .closest(selector) : up 0 or more levels ('span').closest('ul'); ('.bottom').closest('li'); ul li level 1 ul li level 2 li class "bottom" span level /span 3 /li /ul /li /ul /li /ul ul

Move Sideways evAll().prevUntil()

Move Down .children().find()

Filter .filter(selector) .filter('.some-class').filter(function) .filter(function() {return (this).parents('li').length 2; });

Filter .not(selector) .not('.some-class').not(function) .not(function() {return (this).parents('li').length 2; });

Filter .slice() .slice(2).slice(-2).slice(3, 6).slice(2, -1).eq() .eq(2).eq(-2)

Context ('selector', 'context') Different from "or" selector – ('selector1, selector2')Same as ('context').find('selector')Not worth using; too confusing.add().andSelf().end()

Check .hasClass(class).is(selector)** returns a boolean

Traversal Methods List of all traversal methods on the jQuery API sitehttp://api.jquery.com/category/traversing

Chaining JavaScript has chaining built in. 'swap this text'.replace(/w/, -').join('.');jQuery takes advantage of this concept by having almostall methods return the jQuery object.

Chaining Chain traversal methods together ('a').parent('li').siblings().find('a')

Chaining Attach multiple behaviors. ('a').removeClass('old').addClass('new');

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

Chaining JavaScript ignores white space, so use it to your advantage.var lis ('.container ).end(); // unnecessary; added for symmetry

Looping Implicit IterationExplicit Iteration (Looping) ('li').removeClass('myclass');//implicit ('li').each(function(index) {//explicit (this).append( ' #' (index 1) );});

this Keyword Refers to the current objectjQuery sets this to matched elements in the jQuery object. ('li').each(function() {console.log( this ); // DOM elementconsole.log( (this) );});

Tips Store selectors used more than once in variablesUse length property to check existence .but often no need for the checkvar listItems ('li');var numItems listItems.length//no need for length check listItems.addClass('pretty');if (numItems) {// do something with other elements}

Tips Concatenate to pass in a variable ('#menu li').each(function(index) { (this).click(function() { ('#footer li:eq(' index ')').addClass('active');});});

Tips Avoid jQuery's custom selectors when possible// bad (':checkbox')// better ('input:checkbox')// best ('input[type "checkbox"]')

Tips Avoid jQuery's custom selectors when possible// uncool ('div:first')// cool ('div').first();

Tips Avoid jQuery's custom selectors when possible// slower ('li:eq(3)') ('li:lt(3)')// faster ('li').eq(3) ('li').slice(0, 3)

Event Handling

Loading Events (document).ready();.load() Typically used with (window)Also helpful with images, but be careful!

Multiple “Ready”Handlers All are executedExecution takes place in order definedCan even be defined after the document is ready!

Low-level methods.bind() add an event listener to elementscan be a native event like "click"can be a custom event, triggered by other code ('button').bind('click', function(event) {// button got clicked});

Method Context The “this” keywordDOM Elements vs. jQuery Objects ('button').bind('click', function(event) {// this is the button DOM element// this.className ' clicked';// (this) returns jQuery object w/ 1 element// (this).addClass('clicked');});

Low-level methods.trigger() Trigger events programmaticallyWorks for native and custom events ('button').trigger('click');

Low-level methods.bind() and .trigger()// this listens for a click on a span ('span').bind('click', function() {/* this stuff happens when a span is clicked */});// maybe the user will click on a span. Or.// this triggers any click event bound to a span ('span').trigger('click');

Low-level methods.unbind() remove an event listener from elementsremove all listeners, or just the specified one ('button').bind('click', clickListener).bind('click', otherListener);// unbind all click listeners ('button').unbind('click');// unbind only the specified listener ('button').unbind('click', clickListener);

Shorthand Syntax ('button').click(clickListener);// ('button').bind('click', clickListener); ('button').click();// ('button').trigger('click');

Shorthand Syntax ut() .mouseover().mouseout().mouseenter() ve().dblclick() .scroll().resize().error()

Event Propagationa.k.a. “event bubbling”http://www.quirksmode.org/js/events order.html

Event Propagationa.k.a. “event bubbling”http://www.quirksmode.org/js/events order.html

Two Event Tutorials How to ensure that new elements added to the DOM haveevents bound to them. by using event delegation:Working with Events, part 1 ( tinyurl.com/eventdelegation )by re-binding:Working with Events, part 2 ( tinyurl.com/eventrebinding )

Event Propagation Sometimes we don't want events to bubble. Responding to hovers on menus(which, maybe, we shouldn't do anyway)mouseover vs. mouseenter demo

Event delegation alternative event handling architecture scales much bettermakes it trivial to add and remove elementsuses event.target rather than this*(but jQuery's delegation methods map this to event.target)don't ask every element for events, ask a parent insteadeffort is moved from binding to handling

Event Delegation .live() binds an event handler to the document.triggered when element acted upon or one of its ancestorsmatches selector.die() unbinds an event handler

Event Delegation .live() and .die() look just like .bind() and .unbind() ('button').live('click', function(event) {// button got clicked});// unbind click on button ('button').die('click');

Event Delegation Stop using .live() and .die() They are deprecated as of jQuery 1.7They don't work as expected in some situations: ('#wrapper').find('a, span').live('click', fn);They require events to bubble all the way up todocument.But, if you're using them successfully with olderjQuery versions, no worries!

Event Delegation .delegate() binds an event handler to jQuery set.triggered when element indicated in first argument isacted upon or one of its ancestors matches the firstargumentmore "optimized" delegation.undelegate() unbinds an event handler

Event Delegation ('#wrapper').delegate('button', 'click',function(event) {// button got clicked});// unbind click on button ('#wrapper').undelegate('button', 'click');

Event Delegation Use .delegate() and .undelegate() for event delegation injQuery before 1.7.

Event Delegation .on() new in jQuery 1.7the future of jQuery event handlingone event handler method to rule them alluse instead of .bind() and .live() and .delegate().off() unbinds event handlers bound by .on()

Direct Event Binding ('button').on('click', clickListener).on('click', otherListener);;// remove all click listeners ('button').off('click');// remove only the specified listener ('button').off('click', clickListener);

Event Delegation ('#wrapper').on('click', 'button',function(event) {// button got clicked});// remove click listeners ('#wrapper').off('click', 'button');

event object normalized by jQuery to provide consistent informationacross browsersevent.target to access the element that triggered the eventevent.pageX/Y for mouse positionevent.preventDefault() to prevent an event's default actionevent.stopPropagation() to prevent an event from bubblingevent.which to identify which key is pressedmore event properties ct/

event object example prevent the default action from occurringstop the event's propagation up the DOM ('a.toggler').on('click', function(event) {event.preventDefault();event.stopPropagation(); (this).parent().next().slideToggle();// or, return false to both// preventDefault and stopPropagation// (but problematic)});

event object example identify the type of event being triggered ('button').on('mouseenter mouseleave', function(event) {var isEntered event.type 'mouseenter'; ('#something').toggleClass('active-related', isEntered);if (isEntered) {// do one thing} else {// do another}});

event object Very useful for key events event.which : key code normalized by jQueryevent.metaKey : command / on Mac, control on Winevent.altKey : alt / option / on Macevent.ctrlKey : control key everywhereevent.shiftKeykey event demo

event object access newer event types through the original eventif (document.createTouch) { ('body').bind('touchstart touchmove touchend', function(event) {// use the original event:event event.originalEvent;}// pass the first touch object as a second argumentvar touch event.targetTouches[0];sideSwipe[ event.type ](event, touch);});

what? sideSwipe[ event.type ](event, touch);// declare some variables up here (startcoords, endcoords, etc.)var sideSwipe {touchstart: function(event, firstTouch) {startcoords {x: firstTouch.pageX, y: firstTouch.pageY};},touchmove: function(event, firstTouch) {if (event.targetTouches.length 1) {event.preventDefault();endcoords {x: firstTouch.pageX, y: firstTouch.pageY};} else {endcoords startcoords;}},touchend: function(event) {// direction of horizontal swipe?// also, far enough horiz, not too far vert.?// if so, do something}};

what? sideSwipe[ event.type ](event, touch);var sideSwipe {touchstart: function(event, firstTouch) { },touchmove: function(event, firstTouch) { },touchend: function(event) { }};// if event.type equals 'touchstart', then:/*sideSwipe.touchstart() sideSwipe['touchstart']()sideSwipe['touchstart']() sideSwipe[event.type]()*/

Wait! There must be a better way.First argument for .on() and .bind() can accept a map of eventtypes and their handler functionsvar myEvents {focus: function() {alert('focused!');},blur: function() {alert('blurry!');}}; ('input').on( myEvents );

event mapvar sideSwipe {'touchstart touchmove': function(event) {event event.originalEvent;var firstTouch event.targetTouches[0];if (even

Aug 12, 2000 · Jquery Tutorial. Outline . Used by plugins to keep jQuery safe. ('p').slideDown('slow', function() {// code in here is not executed // until after the slideDown is finished // jQuery calls the