This course is out of date and does not reflect our standards or industry best practices. We now recommend you take the Complete Intro to Web Development, v3 course.
Table of Contents
Part 1 - Events in jQuery
Review of Previous Workshop
Refresher on Karl’s contact info. Recap of Workshop #1 - functions, objects and the pillars of jQuery. Overview of workshop: events, DOM manipulation, AJAX and effects Events are the beginning of the “do something” part of jQuery Review of loading Events $(document).ready and $(window).load. Binding to ready fires after document is ready vs. load only fires once Review of when to use load instead of ready Performance tip: anticipatory loadingEvent Binding (and Unbinding)
Low-level method bind for listening to native browser events or custom events Audience asks, “Is there an advantage to using bind vs. native DOM onclick handlers?” Advantage is bind allows you to bind multiple event handlers to the same element. Karl hints at an even better way to bind lots of events Method context (the this keyword) and how wrapping this in a jQuery function, you can use jQuery methods on that element. Karl explains the difference between using jQuery’s addClass vs. native el.className. Audience asks, “Why jQuery doesn’t automatically wrap the element in $()?”Triggering Events
Calling events programmatically with trigger. Lightbulb moment! Trigger can be used to fire custom events Audience asks, “Why use bind instead of click?” Karl explains why bind is clearer to read than shorthand methods (like click) Using unbind to remove multiple or single instance of event handlers. Audience gives examples of when to use unbind Shorthand methods (review)Event Propagation
Events walking up the DOM aka “event bubbling” is event propagation Karl’s two event tutorial articles on Learning jQuery blog: Event propagation demo using mouseover/mouseout & mouseenter/mouseleave Benefit of event delegation is one event handler on a parent element can handle events on its inner elements. Use event.target to find the inner-most element of the eventLive and Die Methods
Brief history of event delegation methods live and die. The live method binds events to document so if the page changes the events will still work. The problem is that document is the worst element to bind to because it has to walk all the way up the page Don’t use live and die anymore. The methods are deprecated as of jQuery 1.7 and don’t work with traversal Event delegation methods delegate and undelegate. Binding event handler to containing element after document is readyEvent Delegation
Karl points out things he actually liked about the live method. You can call it in the <head> section of the page to bind events before the document is even ready $(document).delegate(...) is the same thing as using live Event delegation is great if you want new elements to behave the same as the existing elements in your page Karl demos and explains event delegation further through interactive examples. He also covers more in-depth about DOM objects as per audience questions As of jQuery 1.7, on and off methods now are the methods that provide facilities for all event types (live, die, delegate, undelegate, bind and unbind). “One event handler method to rule them all” on is basically bind, but given an optional second parameter it becomes delegateEvent Object
All events when fired return the event object as the first parameter of your callback. The event object has many helpful properties (event.target, event.pageX/Y, event.preventDefault(), event.stopPropagation(), event.which, etc) event.stopPropagation() vs event.preventDefault() return false calls both but can be problematic (js errors don’t get to return false)Event Object Properties
Using event.type for handling multiple events with only one event handler Handling key events in jQuery (using event.which, event.metaKey, event.altKey, event. ctrlKey & event.shiftKey). Karl uses a tool to demo inspecting event object properties Triggering events programmatically doesn’t give you the same event object propertiesEvent Object Properties, continued
event.timestamp focus and blur events Demoing event.altKey is true when holding alt key and hitting a normal key Access original event object (not jQuery normalized one) with event.orginalEvent. Code example using originalEvent to access native event properties (like touches)Advanced Event Handling Tips
Namespacing events, e.g. on(‘click.namespace’), off(‘.namespace) Bind custom events e.g. on(‘gamestart’) and fire them at will with trigger(‘gamestart’). Example of evented programming and setting event data Audience asks for clarification of namespaces and if you can use multiple namespaces. Karl suggests “yes” but suggests not to use it
Part 2 - DOM Manipulation
Creating elements
$(“<div></div>”) or $(“<div />”) creates a new div that’s disconnected from the DOM Can use second argument to initialize other properties when creating elements. For example, $(“<div />”, { ‘class’: “test”, click: fn }); - Tip: make sure to use quotes around class because it is a reserved word Using appendTo to attach new elements and audience clarification on creating elements Audience asks how to append a lot of elements and Karl codes examplePerformance Tips & Inserting Elements
Tip: dealing with performance issues with JSPerf Use clone to copy elements that already exist. clone(true) copies events and data, too Overview of ways to insert elements Difference of appendTo and append, insertAfter and after is you are either inserting or moving elements append, prepend, after, before, wrap and wrapInner can now accept a function which returns the elements you want to insert Remove elements with the remove, detach and empty methodsContent, Attributes & Properties
Get and replace content with html or text. Get and set values on form inputs with val. Caution: script tags will execute when inserted using html Difference between prop (properties) and attr (attributes). Before 1.6 only attr existed. Attributes exist in the DOM and properties are properties of DOM elements (objects). e.g. className is the property, class is the attribute (what you put in your HTML) Boolean attributes can return an actual boolean (instead of string) with prop Creating DOM elements uses attr behind the scenes (not prop) Get attr(“title”). Set with attr(“title”, “my title”). Set multiple at a time with a map attr({title: “my title”, name: “some_name”}) or use functions attr(‘title’, fn) Careful using prop(‘href ’) which returns fully qualified url Demo of DOM link properties (e.g. a.pathname)CSS Styles and Dimensions
CSS is like attr to set and get CSS style properties, but it’s better to change the class with addClass, removeClass and toggleClass instead of changing individual css properties camelCase css properties without quotes or use dashes inside quotes. For example, css({ backgroundColor: “red”, ‘margin-top’: ‘10px” }) Pass in functions to CSS methods to do computation css(‘font-size’, fn); The width and height methods return a number. The offset returns object with top and left properties relative to the document. The position returns relative to its offset parentData
Associate data with elements using data and removeData methods As of 1.4.4, the data method reads HTML5 data-* attributes and also parses JSON e.g. <div data-foo=”bar”> or <div data-img=’{“alt”:”pic”, “src”:”path/file.jpg”}’> Karl demos how he has used data for lazy-loading images Audience asks if changing the HTML5 data attribute updates the jQuery data method. Answer is no. data. Use HTML5 data attribute as a starting point to set the data Audience asks how Karl feels about dashes converting to camelCase data. Karl says spec wasn’t clear and part of it is implementing features before there is a spec.
Part 3 - Ajax
$.ajax Options and Shortcut Methods
Core ajax method is $.ajax which has a ton of options Walk-through of main ajax options: Not setting url will use current url. You can now set url using $.ajax(url, options) Example of collecting form data with $(form).serialize() dataType specifies what type of data you’ll get back (“json”, “html”, “text”, etc). “jsonp” dataType allows get data cross-domain (Twitter API, Flickr, etc). Karl demos API search tool and how to hack your own JSONP service using iframe. http://api.jquery.com/jQuery.ajax/ for more $.ajax options Audience asks, “do you see anything in the browser when $.ajax is called?” Karl explains you have to do use the response data to build HTML to see something $.ajaxSetup() globally configures all $.ajax settings$.ajax Responses
Before 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 interface (jqXHR subset of xhr), a Deferred object. Read more about deferreds: http://api.jquery.com/category/deferred-object/ Instead of using options use done, fail and always methods. Using them you can add multiple handlers. If ajax has been completed they will fire method immediately (like document ready)Multiple Handlers & Promises
Attach multiple handlers using: request.done(fn1, fn2...) request.done([fn1, fn2...]) or request.done(fn1).done(fn2).done(...) Karl walks through using promise interface to cache ajax requests in a nice wayShortcut methods and Q&A
Audience asks to improve the example using error handling Audience asks about synchronous ajax requests. Karl says don’t use them because it blocks all other JavaScript and suggests to just block the user with a modal dialog Shortcut methods ($.get, $.post, $.getJSON, $.getScript) - Karl doesn’t use them anymore. He recommends to just use $.ajax load method to request html and grab a fragment of it with a selector. Karl and Marc reminisce about Resig’s initial excitement of his load method
Part 4 - Effects and Animations
Basic Methods and Callbacks
Don’t be obnoxious with effects fadeIn, fadeOut, fadeToggle, fadeTo are nice for showing overlay elements. slideDown, slideUp, slideToggle can be less jarring than no animation show/hide Callbacks are executed at end of animations once for each element slideUp(fn). You can use a promise slideDown(250).promise().done(fn) Animations go in sequence for multiple animations or in parallel for different elements Custom animations and running multiple animations in parallelAnimating Properties and Easing
Properties can be animated by number, percent or relatively (“+=200px”, “-=20%”, etc) You can’t animate the “left” without changing it’s CSS position: relative or absolute Custom animation options (duration, easing, complete, step, queue and specialQueue) More easing types available with jQuery UI or Demo of animation callbacks firing immediately if animations are done Advanced animation with per-property easing Currently animated selector is(‘:animated’)Stop/Delay and Global Settings
stop method can stop current animations from continuing and jump to the end of the animation (clearQueue and gotoEnd boolean options) and demo delay method can delay execution of an animation for a specified period of time Global duration changes all animations default ($.fx.speeds._default = 250)