2-swedberg-jquery_indepth
TRANSCRIPT
-
8/13/2019 2-swedberg-jquery_indepth
1/7
Karl Swedberg: jQuery In-Depth
Part 1: Events in jQueryReview o Previous WorkshopReresher on Karls contact ino. Recap o Workshop #1: unctions, objects and the pil-lars o jQuery. Overview o workshop: events, DOMmanipulation, AJAX and effects
Events are the beginning o the do something part o jQuery
Review o loading Events $(document).readyand $(window).loadBinding to ready fires afer document is ready vs load only fires once
Review o when to use loadinstead o ready
Perormance tip: anticipatory loading
Viewer note: screencast is 10 seconds behind for about 10 minutes before it catches up
Event Binding (and Unbinding)Low-level method bindor listening to native browser events or custom events
Audience asks, is there an advantage to using bindvs native DOM onclick handlers?Advantage is bindallows you to bind multiple event handlers to the same element
Karl hints at an even better way to bind lots o events
Method context (the thiskeyword) and how wrapping thisin a jQuery unction, youcan use jQuery methods on that element.Karl explains the difference between using jQuerys addClassvs native el.className.Audience asks, why jQuery doesnt automatically wrap the element in $()?
Calling events programmatically with triggerLightbulb moment! triggercan be used to fire custom events
Audience asks, why use bindinstead o click?
Karl explains why bindis clearer to read than shorthand methods (like click)
Using unbindto remove multiple or single instance o event handlersAudience gives examples o when to use unbind
Shorthand methods (review)
0:00:00 0:02:49
0:02:50 0:03:24
0:03:25 0:07:32
0:07:33 0:08:50
0:08:51 0:09:50
1
0:09:51 0:10:47
0:10:48 0:12:52
0:12:53 0:16:12
0:16:13 0:17:34
0:17:35 0:20:07
0:20:08 0:23:47
0:23:48 0:25:41
-
8/13/2019 2-swedberg-jquery_indepth
2/7
0:25:42 0:28:40
0:28:41 0:29:00
0:29:01 0:32:45
0:32:46 0:35:49
0:35:50 0:39:52
0:39:53 0:41:58
0:41:59 0:44:33
0:44:34 0:46:49
0:46:50 0:47:08
0:47:09 0:47:51
0:47:52 0:58:00
0:58:01 0:58:00
Event Propagation and DelegationEvents walking up the DOM aka event bubbling is event propagation
Karls two event tutorial articles on Learning jQuery blog:http://tinyurl.com/eventdelegation& http://tinyurl.com/eventrebinding
Event propagation demo using mouseover/mouseout& mouseenter/mouseleave
Benefit o event delegation is one event handler on a parent element can handle eventson its inner elements. Use event.targetto find the inner-most element o the event
Brie history o event delegation methods liveand die. Te live method binds events todocument so i the page changes the events will still work. Te problem is that documentis the worst element to bind to because it has to walk all the way up the page
Dont use live and dieanymore. Te methods are deprecated as o jQuery 1.7 and dontwork with traversal
Event delegation methods delegateand undelegate. Binding event handler to containingelement afer document is ready
Karl points out things he actually liked about the livemethod. You can call it in the section o the page to bind events beore the document is even ready
$(document).delegate(...) is the same thing as using live
Event delegation is great i you want new elements to behave the same as the existing ele-ments in your page
Karl demos and explains event delegation urther through interactive examples. He alsocovers more in-depth about DOM objects as per audience questions
As o jQuery 1.7, onand offmethods now are the methods that provide acilities or allevent types (live, die, delegate, undelegate, bind and unbind)One event handler method to rule them allonis basically bind, but given an optional second parameter it becomes delegate
Event ObjectAll events when fired return the eventobject as the first parameter o your callback. Teeventobject has many helpul properties (event.target, event.pageX/Y,event.preventDeault(), event.stopPropagation(), event.which, etc)http://api.jquery.com/category/events/event-object/
event.stopPropagation() vs event.preventDeault()return alse calls both but can be problematic (js errors dont get to return alse)
Using event.typeor handling multiple events with only one event handler
0:58:01 1:03:20
1:03:21 1:07:35
1:07:36 1:09:59
2
http://tinyurl.com/eventdelegationhttp://tinyurl.com/eventrebindinghttp://api.jquery.com/category/events/event-object/http://api.jquery.com/category/events/event-object/http://tinyurl.com/eventrebindinghttp://tinyurl.com/eventdelegationhttp://tinyurl.com/eventdelegation -
8/13/2019 2-swedberg-jquery_indepth
3/7
Handling key events in jQuery (using event.which, event.metaKey, event.altKey, event.ctrlKey& event.shifKey). Karl uses a tool to demo inspecting event object properties
riggering events programmatically doesnt give you the same event object properties
event.timestamp
ocusand blurevents
Demoing event.altKeyis true when holding alt key and hitting a normal key
Access original event object (not jQuery normalized one) with event.orginalEventCode example using originalEvent to access native event properties (like touches)
Advanced Event Handling TipsNamespacing events, e.g. on(click.namespace), off(.namespace)
Bind custom events e.g. on(gamestart) and fire them at will with trigger(gamestart)Example o evented programming and setting event data
Audience asks or clarification o namespaces and i you can use multiple namespaces.Karl suggests yes but suggests not to use it
Part 2: DOM ManipulationCreating elements$() or $() creates a new div thats disconnected rom the DOM
Can use second argument to initialize other properties when creating elementse.g. $(, { class: test, click: n });ip: make sure to use quotes around class because it is a reserved word
Using appendToto attach new elements and audience clarification on creating elements
Audience asks how to append a lot o elements and Karl codes example
ip: dealing with perormance issues with http://jsper.com
Use cloneto copy elements that already exist. clone(true) copies evevnts and data, too
Inserting elementsOverview o ways to insert elements
Difference o appendToand append, insertAferand afer is you are either inserting ormoving elements
1:10:00 1:13:14
1:13:15 1:14:49
1:14:50 1:15:33
1:15:34 1:16:01
1:16:02 1:17:50
1:17:51 1:24:32
1:25:11 1:29:33
1:27:04 1:33:20
1:33:21 1:34:32
1:34:42 1:37:00
1:37:01 1:38:31
1:38:32 1:44:04
1:44:05 1:47:40
1:47:41 - 1:49:27
1:49:28 1:50:32
3
1:50:33 1:51:35
1:51:36 1:52:36
http://jsperf.com/http://jsperf.com/ -
8/13/2019 2-swedberg-jquery_indepth
4/7
append, prepend, afer, beore, wrap and wrapInner can now accept a unction whichreturns the elements you want to insert
Remove elements with the remove, detachand emptymethods
Content, Attributes & PropertiesGet and replace content with htmlor text. Get and set values on orm inputs with valCaution: script tags will execute when inserted using html
Difference between prop(properties) and attr(attributes)Beore 1.6 only attrexistedAttributes exist in the DOM and properties are properties o DOM elements (objects).e.g. classNameis the property, classis the attribute (what you put in your HML)
Boolean attributes can return an actual boolean (instead o string) with prop
Creating DOM elements uses attrbehind the scenes (not prop)
Get attr(title). Set with attr(title, my title). Set multiple at a time with a mapattr({title: my title, name: some_name}) or use unctions attr(title, n)
Careul using prop(hre) which returns ully qualified url
Demo o DOM link properties (e.g. a.pathname)
CSS Styles and Dimensionscssis like attrto set and get CSS style properties, but its better to change the class withaddClass, removeClassand toggleClassinstead o changing individual css properties
camelCase css properties without quotes or use dashes inside quotescss({ backgroundColor: red, margin-top: 10px })
Pass in unctions to CSS methods to do computation css(ont-size, n);
widthand heightmethods returns a numberoffsetreturns object with top and lef properties relative to the document
positionreturns relative to its offset parent
DataAssociate data with elements using dataand removeDatamethodsAs o 1.4.4, the datamethod reads HML5 data-* attributes and also parses JSONe.g. or
Karl demos how he has used data or lazy-loading images
1:52:37 1:52:57
1:52:58 1:53:56
4
1:53:57 1:55:17
1:55:18 1:58:29
1:58:30 2:03:04
2:03:05 2:03:46
2:03:47 2:06:07
2:06:08 2:07:46
2:07:47 2:13:29
2:13:30 2:14:55
2:14:56 2:16:06
2:16:07 2:17:05
2:17:06 2:21:17
2:21:18 2:24:27
2:24:28 2:27:47
-
8/13/2019 2-swedberg-jquery_indepth
5/7
Q&AAudience asks i changing the HML5 data attribute updates the jQuery datamethod.Answer is no. data. Use HML5 data attribute as a starting point to set the data
Audience asks how Karl eels about dashes converting to camelCase data.Karl says spec wasnt clear and part o it is implementing eatures beore there is a spec
Note: http://pres.learningjquery.com/emasters/examples/ has more demos and examplessuch as element insertion demos
Part 3: Ajax$.ajax Options and Shortcut MethodsCore ajax method is $.ajax which has a ton o options
Walk-through o main ajax options: Not setting urlwill use current url
You can now set urlusing $.ajax(url, options)
Example o collecting orm datawith $(orm).serialize()
dataTypespecifies what type o data youll get back (json, html, text, etc)jsonp dataTypeallows get data cross-domain (witter API, Flickr, etc)Karl demos API search tool and how to hack your own JSONP service using irame
http://api.jquery.com/jQuery.ajax/or more $.ajaxoptions
Audience asks, do you see anything in the browser when $.ajaxis called?Karl explains you have to do use the response data to build HML to see something
$.ajaxSetup() globally configures all $.ajax settings
$.ajax ResponsesBeore jQuery 1.5, response handlers could were set as options (success, error, complete)
Make sure to handle errors (think network outages)
Now $.ajax returns a promise interace (jqXHR subset o xhr), a Deerred objectRead more about deerreds: http://api.jquery.com/category/deerred-object/
Instead o using options use done, ailand alwaysmethodsUsing them you can add multiple handlersI ajax has been completed they will fire method immediately (like document ready)
Attach multiple handlers using: request.done(n1, n2...) request.done([n1, n2...]) orrequest.done(n1).done(n2).done(...)
5
2:27:48 2:28:50
2:28:51 2:30:40
2:32:19 2:33:32
2:33:33 2:34:40
2:34:41 2:36:45
2:36:46 2:44:45
2:36:46 2:46:24
2:46:25 2:47:00
2:47:01 2:48:15
2:48:16 2:49:02
2:49:03 2:50:06
2:50:07 2:52:03
2:52:04 2:53:11
http://pres.learningjquery.com/femasters/examples/http://api.jquery.com/jQuery.ajax/http://api.jquery.com/category/deferred-object/http://api.jquery.com/category/deferred-object/http://api.jquery.com/jQuery.ajax/http://pres.learningjquery.com/femasters/examples/ -
8/13/2019 2-swedberg-jquery_indepth
6/7
Karl walks through using promise interace to cache ajax requests in a nice way
Audience asks to improve the example using error handling
Audience asks about synchronous ajax requests. Karl says dont use them because itblocks all other JavaScript and suggests to just block the user with a modal dialog
Shortcut methods ($.get, $.post, $.getJSON, $.getScript) - Karl doesnt use them any-more recommends to just use $.ajax
loadmethod to request html and grab a ragment o it with a selectorKarl and Marc reminisce about Resigs initial excitement o his loadmethod
Part 4: Effects and Animations
Basic Methods and CallbacksDont be obnoxious with effects
adeIn, adeOut, adeToggle, adeToare nice or showing overlay elementsslideDown, slideUp, slideTogglecan be less jarring than no animation show/hide
Callbacks are executed at end o animations once or each element slideUp(n)You can use a promise slideDown(250).promise().done(n)
Animations go in sequence or multiple animations or in parallel or different elements
Custom animations and running multiple animations in parallel
Animating Properties and EasingProperties can be animated by number, percent or relatively (+=200px, -=20%, etc)
You cant animate the lef without changing its CSS position: relative or absolute
Custom animation options (duration, easing, complete, step, queue and specialQueue)
More easing types available with jQuery UI or http://gsgd.co.uk/sandbox/jquery/easing/
Demo o animation callbacks firing immediately i animations are done
Advanced animation with per-property easing
Currently animated selector is(:animated)
6
2:53:12 3:00:52
3:00:53 3:05:24
3:05:25 3:07:35
3:07:36 3:08:23
3:08:24 3:11:43
3:11:52 3:12:40
3:12:41 3:13:23
3:13:24 3:14:32
3:14:33 3:17:19
3:17:20 3:19:31
3:19:32 3:20:55
3:20:56 3:21:51
3:21:52 3:22:34
3:22:35 3:22:54
3:22:55 3:24:36
3:24:37 3:26:31
3:26:32 3:27:00
http://gsgd.co.uk/sandbox/jquery/easing/http://gsgd.co.uk/sandbox/jquery/easing/ -
8/13/2019 2-swedberg-jquery_indepth
7/7
Stop/Delay and Global Settingsstopmethod can stop current animations rom continuing and jump to the end o theanimation (clearQueue and gotoEnd boolean options) and demo
delaymethod can delay execution o an animation or a specified period o time
Global duration changes all animations deault ($.x.speeds._deault= 250)
Global Off can disable all animations ($.x.off)Animations occur in 0 milleseconds
3:27:01 3:29:43
3:29:44 3:30:08
3:30:09 3:30:56
3:30:57 3:34:58