jQuery 101

advertisement
Robert Boedigheimer
Web developer since 1995
Pluralsight Author
3rd Degree Black Belt, Tae Kwon Do
ASP.NET MVP
http://aspadvice.com/blogs/robertb/
boedie@outlook.com
@boedie
Free, open source, lightweight library that
simplifies JavaScript development
Cross browser
DOM manipulation
AJAX
Leverage existing skills (CSS, HTML)
“Make common tasks trivial”
Rich plugin community that extends core library
1.9+
Removed previously deprecated features (jQuery
Migrate Plugin)
Supports IE 6+
http://jquery.com/upgrade-guide/1.9/
2.0+
Same API as 1.9
Supports IE 9+
“Restores deprecated features and behaviors so
that older code will still run properly on jQuery
1.9 and later”
Uncompressed version has diagnostics
Writes warnings to developer tools console
jQuery.migrateWarnings
“We recommend that you always start by
including the jQuery Migrate plugin to see if it
gives you any warnings”
jQuery.com
Production – minified/gzipped, ~32KB
Debug - ~252KB
Place in web site, reference like any other
JavaScript file
<script src=“…” >
$ is alias of jQuery
Chose to replace the Microsoft Ajax Library
Full product support
Pledged to not “fork” jQuery (included “as-is”)
Contribute like anyone else (templates, etc)
Included since Visual Studio 2010
IntelliSense support
Design time feature
Download “jQuery-version-vsdoc.js” from
http://tinyurl.com/pv2szek
Traditional <body onload=“ “> does not fire until all
parts of the page are downloaded (.js, .css, images)
$(document).ready(function( ) {
//Code to run
});
$(function() {
//Code to run
});
$(“#id”) – element id
$(“.class”) – element(s) class
$(“E”)
$(“E D”) – descendent
$(“E > C”) – direct child C
$(“E[A=V]”) - attribute value V
$(“E[A$=V]”) – attribute ends V
$(“E[A^=V]”) – attribute begins V
$(“E[A*=V]”) – attribute contains V
:first, :last
:first-child, :last-child
:eq(2) – 3rd element matched
:gt(5) – 6th and greater elements matched
:even, :odd
:button
:not(filter)
:image
:selected
:submit
:visible
:contains
:has
Ability to continue to tack on commands to an
existing set of elements
Supports “fluent interface”
More compact representation
attr( ) – get or set attribute values of matched
element(s)
Normalized some of the attribute names for crossbrowser consistency
Pass a function which will be invoked and its return
value is attribute value
addClass( ), removeClass( ), css( )
.html( ), .text( )
appendTo( ), prependTo( )
insertBefore( ), insertAfter( )
$(“… html …”).insertAfter(“#id”)
clone( )
remove( ), after( ), replaceWith()
.trim( ) – remove leading/trailing spaces
.inArray( ) – returns first index of match in an
array
.extend( ) – adds properties from other objects
to an object
bind( ) – event attached directly to element
click( ), dblclick( ), etc
live( ) – event attached at document level
(deprecated)
delegate() – event attached to a ancestor of
choice
on( ) – newest, others implemented using these
Event object has properties that are consistent
cross-platform
preventDefault( ) will cancel whatever the
browser would have natively done
show(), hide()
fadeIn(), fadeOut()
slideDown( ), slideUp( )
animate( ) – CSS style properties with numeric
values only
Rotate with various transitions through a series
of images
Zoom
Curtains
Fade in
Scroll
http://malsup.com/jquery/cycle/
Popup dialog box for web sites
Gray out the background
http://jquery.com/demo/thickbox/
Show a portion of a set of images with previous
and next navigation
http://tinyurl.com/4cdghoq
Display content based on filter criteria
Animations to show/hide matches
http://tinyurl.com/4wzd8ra
Move mouse around an image and see an
zoomed in version of a portion of it
Original larger photo with details
Smaller version of the photo to show on the page
http://www.mind-projects.it/projects/jqzoom/
Round images or general elements like <div>
http://www.steamdev.com/imgr/ (images)
http://jquery.malsup.com/corner/ (general)
Limit the number of characters allowed and give
user feedback on how many can entered
http://tinyurl.com/655rf2
Ability to have children of a parent element be
resized to all be the same height (tallest)
http://tinyurl.com/6hztw4
Overlay with more info appears when hover
over an image
http://tinyurl.com/llogjx
jQuery plugin and modified HTML to request
images as scroll down
data-original – set to image URL
src – set to 1x1 clear pixel image
Pages with lots of images only load those
“above the fold”
http://www.appelsiini.net/projects/lazyload
Set of core UI effects and widgets
Widgets
Accordion
Dialog
Datepicker
Tabs
Interactions
Drag and drop
Selectable
Resizable
jqueryUI.com (customize download)
Client side data binding
https://github.com/BorisMoore/jsrender
.get( ), .getJSON( ), .post( ) – functions that
make calls and invoke callbacks
.load( ) – AJAX call that returns HTML and
automatically updates DOM with new content
.ajax( ) – most options
.ajaxSetup( ) – set common options
Ajax events – ajaxStart, ajaxComplete, ajaxError,
ajaxSuccess
Turn off the right click menu at a document or
element level
Avoid multiple orders, add to carts, etc when a
customer thinks they need to double click web
buttons
Use simple jQuery animation to hide the button
on the first click
Often need to show additional information or
form controls
Select a dropdown value or button, now need
to ask for more information
Allow the user to choose the stylesheet to use
Apply on the client
Convert a DOM object to a jQuery wrapped
object
$(domElement)
Convert from a jQuery wrapped object (single
match) to a DOM object
jQueryObject.get(0)
jQueryObject.[0]
Add functionality to enhance what is already
available in base library
Follow a specific pattern to allow use of $ to
mean jQuery within function definition
Assign function to $.fn
Return the wrapped set to allow chaining
(unless need to return a specific value)
JavaScript library that detects support for new
HTML5 and CSS 3 features
Use latest features, or fallback to polyfills/shims
http://www.modernizr.com/
Check if an element is present
Check if a set of elements matches another
selector
:visible
:hidden
Use chaining
Don’t need to search again for the same
DOM manipulation is expensive, do as infrequently
as possible
Use caching
Use selector and save result
Use result multiple times without having to search
again
Selector performance (fastest first)
id
element
class
pseudo
Content Delivery Network (CDN)
Improve performance for users
Reduce bandwidth and server load
Options
jQuery
Google
Microsoft
http://code.jquery.com/jquery-latest.min.js
Minimize JavaScript and combine
Remove whitespace, comments, excessive
semicolons, etc
Combine files to reduce HTTP requests
http://aspalliance.com/1992
Microsoft Ajax Minifier (Codeplex.com)
Command line, .dll, and build tasks
Test after minimize!
Combine files with MSBuild
Runtime (but results cached in memory)
Default order
Common libraries first (jQuery, etc)
Alphabetical
Multiple bundles are ok
API
Customize ordering of files
Customize transforms (CoffeeScript, LESS, etc)
Previously had large amount of JavaScript injected
into HTML when used validators
JavaScript moved to external script
Uses “data-” attributes
Control attributes so accessible on client, such as dataval-display=“Dynamic“ for Display=“Dynamic”
Not used by default, opt in via web.config
ValidationSettings:UnobtrusiveValidationMode
PM> Install-Package
Microsoft.ScriptManager.jQuery
http://jquerymobile.com/
UI framework based on jQuery
For smartphones (and tablets, not desktops)
Progressive Enhancement
Themes
Uses HTML 5 “data-” attributes
Physical page can contain multiple “pages”
http://jQuery.com
“jQuery in Action”, Bibeault and Katz
“jQuery Cookbook”
“Learning jQuery”, Chaffer and Swedberg
Pluralsight Course – “Useful jQuery Plugins”
http://tinyurl.com/ntclewv
http://learn.appendto.com/lessons
http://aspadvice.com/blogs/robertb/
boedie@outlook.com
@boedie
Download