-
Ben Nadel
-
Chief Software Engineer, Epicenter Consulting
-
Author of Kinky Solutions blog (www.bennadel.com)
-
Adobe Community Expert
-
Adobe Certified ColdFusion Developer
-
Co-Manager New York ColdFusion User Group
-
ColdFusion, XHTML, CSS, Javascript Developer
-
What Is jQuery?
jQuery is a fast and concise Javascript library that simplifies:
-
DOM Traversal for both XHTML and XML
-
DOM Manipulation
-
Event Handling
-
UI Effects / Animation
-
AJAX
Designed to make rich user interface development fast, easy, and
cross-browser compatible!
-
jQuery UI Effects - Pain Free Animation
jQuery has a whole UI library of interaction effects and widgets (ex. Draggable, Sortable, Tabs, Accordion).
There are also a number of core UI effects that are super easy to work with:
-
Why I Didn't Like jQuery At First
When jQuery was first demonstrated to me, I thought it was lame!
Nothing but UI effects.
-
I'm primarily a back-end developer
-
I don't know much about design
-
Fear Response: Do I have to become a designer?
-
Fear Response: Even after years of JS development, I can't do the stuff I see jQuery do
-
No meeting half-way: Development & Design
-
jQuery For Developers
-
Most jQuery code is non-UI related
-
It takes things you can already do, and makes them better, faster, and more cross-browser compatible!
-
It creates unified facades to aspects of Javascript that are still different from browser to browser,
while at the same time leveraging browser-specific efficiencies
-
Pain-Free UI Effects: Once we get a
handle on the core jQuery features, it is almost no effort for us developers
to add "web 2.0" style bells and whistles
-
Really small API!
-
Now, On To The Awesome Stuff!
UI Effects are interesting, but let's mess with the DOM!
-
jQuery Foundations: Anonymous Methods
-
jQuery makes heavy use of anonymous methods
-
Anonymous methods are nameless methods declared at runtime
-
$( function(){ alert( "I'm anonymous!" ); } );
-
Used for event handlers, callbacks, iteration, etc.
-
jQuery Foundations: $() Factory Method
-
$() method is a short-hand notation for jQuery() factory method
-
$( function ) - executes given method once DOM has loaded
-
$( elements ) - returns jQuery stack containing given elements
-
$( selector ) - returns jQuery stack containing elements matched by the given selector
-
$( html ) - returns jQuery stack containing new elements represented by the HTML
-
jQuery Foundations: $() Wraps DOM Elements
-
jQuery does not alter core DOM features
-
jQuery wraps DOM elements inside instances of the jQuery object (jQuery stack)
-
You can get access to the contained elements
-
$( .. )[ 0 ] == $( .. ).get( 0 )
-
jQuery Selectors: $( "selectors" )
Find DOM elements based on element type, attribute values, class names, meta-location, and contextual relationship
-
$( "#header" ) - Returns collection containing element with ID=header
-
$( "div.note" ) - Returns collection of all DIV tags with class "note"
-
$( "p" ) - Returns collection of all P tags
-
$( "ul.list li" ) - Returns collection of all LI tags contained within the UL with class "list"
-
$( "a:first" ) - Returns collection containing first A tag
-
$( "a[ rel = 'home' ]" ) - Returns collection containing A tags with REL attribute "home"
-
... and dozens more!
-
Think CSS!
-
jQuery Selectors: $( "selectors" ) ... continued
Take a moment to reflect on just how awesome jQuery selectors are
No more custom function to find stuff:
-
getParentWithClass()
-
getParentWithTagName()
-
Working With The $() Collection
-
$() returns a jQuery collection containing 0+ elements
-
Calls on an empty collection don't error
-
When accessing values, usually only the first element is used
-
When mutating values, usually all elements in collection are updated
-
When mutating values, the jQuery object is usually returned - this allows for method chaining
-
$().addClass( "one" ).addClass( "two" ).removeClass( "one" )
-
NOTE: Method chaining is "cool", but can hurt readability - don't overuse
-
Working With The $() Collection - Attributes & Values
-
$().attr( name ) - Gets value of given attribute for first element
-
$().attr( name, value | {options} ) - Sets values for all elements
-
$().addClass() - Adds CSS class to all elements
-
$().removeClass() - Removes CSS class from all elements
-
$().css( name ) - Gets CSS value of given property for first element
-
$().css( name, value | {options} ) - Sets CSS properties for all elements
-
$().html() - Gets the inner HTML of the first element
-
$().html( html ) - Sets the inner HTML of all elements
-
$().text() - Gets the combined text of all elements
-
$().text( text ) - Sets the text value of all elements
-
$().val() - Gets the value attribute of first element
-
$().val( val ) - Sets the value attribute of all elements
-
Working With The $() Collection - Moving Elements
-
$().append( html | element | jQuery ) - adds given content to the selected content
-
$().appendTo( selector ) - adds given set to the selected set
-
$().prepend() / $().prependTo() - Same as above, but prepends
-
$().before( content ) - Inserts the given content before the selected elements
-
$().after( content ) - Inserts the given content after the selected elements
-
$().remove() - Removes selected elements from DOM
-
$().empty() - Removes all children from given set of elements
-
$().clone() - Creates a copy of the given set
-
... many more!
-
Working With The $() Collection - Traversing The DOM
-
Working With The $() Collection - Filtering The Stack
-
$().filter( selectors | function ) - Returns a sub-set of collection matching filter
-
$().not( selectors ) - Returns a sub-set of collection not matching filter
-
Filtering methods are non-destructive - filter returns new collection leaving
original collection unchanged
-
Working With The $() Collection - Iterating Over The Stack
-
Usually, we can work with stack as a whole, but sometimes we need item-specific control
-
$().each( function( intIndex, objElement ) ) -
Executes given method for each element of the collection
-
In context of function, this keyword points to current DOM element
-
NOTE: jQuery provides utility methods to do this with other objects
-
$.each( object, fn( i, val ) ) - Iterates over each key/index in object
-
jQuery Closures - Some Awesome Voodoo Magic!
-
Javascript closures are one of the most powerful features of jQuery
-
A Closure is created when a function reference is made available outside the parent context
-
This prevents parent context from being garbage collected
-
Closures are created whenever you pass an anonymous function in jQuery
-
Our previous $().each() example:
-
Step-by-step Closure Visualization (from www.benandel.com):
Plain jQuery code:
Nested Functions:
Access To Parent Context:
Passed Away From Parent Context:
-
jQuery Event Binding / Triggering
-
You can bind as many handlers to a given event
-
$().bind( eventType, function( objEvent ){} ) - Bind given function to given event type on given collection
-
Many built-in short hands: $().bind( "click", fn ) == $().click( fn )
-
$().trigger( eventType ) - Manually trigger event handlers
-
Many built-in short hands: $().trigger( "click" ) == $().click()
-
return( false ) - In event handler, prevents default behavior and event bubbling
-
objEvent.preventDefault() - In event handler, prevents default event (allows bubbling)
-
objEvent.stopPropagation() - In event handler, prevents bubbling (allows default behavior)
-
NEW: live() / die() - Automatically wires events based on selectors
-
jQuery Custom Event Types
-
jQuery AJAX - HTML / Text / JSON / XML / Script
-
Provides both high-level and low-level control over AJAX requests
-
$().load( url, [data], [callback] ) - Most high-level method - loads the URL contents into the given collection
-
$.ajax( options ) - Most low-level method - completely customizable AJAX request
-
$.get( url, [data], [callback], [type] ) - Performs simple AJAX GET with success callback
-
$.getJSON( url, [data], [callback] ) - Like above, but evaluates data as JSON
-
$.getScript( url, [callback] ) - Loads a remote script and executes it
-
$.post( url, [data], [callback], [type] ) - Performs a simple AJAX POST with success callback
-
jQuery AJAX - Monitoring The Request
-
jQuery Data() - Binding Elements And Data
-
As we start to create thicker client layers and AJAX-heavy functionality, we need to start keeping track of functional data
-
Can use hidden input fields - requires FORM parent
-
Can hack HTML attributes to hold meta data (ex. class="button id:34")
-
$().data( key, value ) - Binds the given key-value pair to the collection
-
$().data( key ) - Returns the bound value for the first element in collection
-
$().removeData( key ) - Removes the bound value from the collection
-
No way to get collection of data()-bound keys
-
Extending jQuery - Plugins And Selectors
-
If jQuery doesn't have a particular feature, it's really easy to add
-
Can extend utility functions (extend $ object)
-
Can extend collection functions (extend $.fn object)
-
Can extend selectors (extend $.expr[':'] object)
-
Huge library of existing plugins!
-
jQuery Does Not Replace Your Skills!
-
As I hope you see, jQuery is awesome!
-
It's not meant to replace your Javascript
-
It's meant to be a tool used to develop better Javascript
-
jQuery Resources
-
http://www.jquery.com - Main site
-
http://docs.jquery.com - Documentation
-
http://api.jquery.com - API Explorer (personally, I find docs more usable)
-
http://ui.jquery.com - jQuery-based user interface downloads / demos
-
http://plugins.jquery.com - Collection of user-submitted plugins
Need to raffle something?
-
Thank You For Listening
-
Ben Nadel
-
Blog: http://www.bennadel.com
-
Email: ben@bennadel.com
-
Ask Ben: http://www.bennadel.com/ask-ben
-
Consulting: http://www.epicenterconsulting.com