How I Learned to Stop Worrying and Love jQuery (Jan 2013)

39
How I Learned To Stop Worrying and Love jQuery David Giard, Sogeti USA C# MVP MCTS, MCSD, MCSE, MCDBA DavidGiard.com @DavidGiard

Transcript of How I Learned to Stop Worrying and Love jQuery (Jan 2013)

Page 1: How I Learned to Stop Worrying and Love jQuery (Jan 2013)

How I LearnedTo Stop Worryingand Love jQuery

David Giard, Sogeti USAC# MVPMCTS, MCSD, MCSE, MCDBA

DavidGiard.com@DavidGiard

Page 2: How I Learned to Stop Worrying and Love jQuery (Jan 2013)

BEFORE

Page 3: How I Learned to Stop Worrying and Love jQuery (Jan 2013)

AFTER

Page 4: How I Learned to Stop Worrying and Love jQuery (Jan 2013)

JavaScript in your page

• <script type="text/javascript"> … </script>

• <script type="text/javascript“ src=“xxx.js"> </script>

Page 5: How I Learned to Stop Worrying and Love jQuery (Jan 2013)

JavaScript: The Good Parts

• Interactive web pages• Fast• Ajax

Page 6: How I Learned to Stop Worrying and Love jQuery (Jan 2013)

JavaScript: The Bad Parts

• Cross-browser issues• Cross-platform issues

Page 7: How I Learned to Stop Worrying and Love jQuery (Jan 2013)

JavaScript Frameworks

• jQuery• Prototype• Dojo• Mootools• ExtJs• etc…

jQuery

Page 8: How I Learned to Stop Worrying and Love jQuery (Jan 2013)

jQuery

• JavaScript Abstraction• Cross-Browser• Built-In Functions• Fast• Unobtrusive• Popular• Ships with Visual Studio 2010 and 2012

Page 9: How I Learned to Stop Worrying and Love jQuery (Jan 2013)

jQuery Popularity

Source: http://royal.pingdom.com

Page 10: How I Learned to Stop Worrying and Love jQuery (Jan 2013)

jQuery Popularity

Source: http://royal.pingdom.com

Page 11: How I Learned to Stop Worrying and Love jQuery (Jan 2013)

jQuery Popularity• Twitter.com• Wikipedia.org• MLB.com• Amazon.com• Bing.com• Microsoft.com• Bit.ly• ESPN.com• Digg.com• Reddit.com• Netflix.com• WordPress.com

Page 12: How I Learned to Stop Worrying and Love jQuery (Jan 2013)

Unobtrusive JavaScript• Obtrusive

<a href=“” onclick=“DoSomething();”> Click Me</a>

• Unobtrusive<script type="text/javascript"> $(document).ready(function(){ $(“#Link1”).click(function(){

DoSomething(); }); </script>

<a href=“” id=“Link1”> Click Me </a>

Page 13: How I Learned to Stop Worrying and Love jQuery (Jan 2013)

Enable jQuery

• Download from jQuery.com• <script

type="text/javascript"

src="scripts/jquery-1.8.3.min.js"></script>

Page 14: How I Learned to Stop Worrying and Love jQuery (Jan 2013)

Content Delivery Network• <script

type="text/javascript" src=“http://ajax.microsoft.com/ajax/jquery/jquery-1.8.3.min.js"></script>

• <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

• <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js "></script>

Page 15: How I Learned to Stop Worrying and Love jQuery (Jan 2013)

/*! * jQuery JavaScript Library v1.8.2 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * * Date: Thu Sep 20 2012 21:13:05 GMT-0400 (Eastern Daylight Time) */(function( window, undefined ) {var// A central reference to the root jQuery(document)rootjQuery,

// The deferred used on DOM readyreadyList,

// Use the correct document accordingly with window argument (sandbox)document = window.document,location = window.location,navigator = window.navigator,

// Map over jQuery in case of overwrite_jQuery = window.jQuery,

// Map over the $ in case of overwrite_$ = window.$,

// Save a reference to some core methodscore_push = Array.prototype.push,core_slice = Array.prototype.slice,core_indexOf = Array.prototype.indexOf,core_toString = Object.prototype.toString,core_hasOwn = Object.prototype.hasOwnProperty,core_trim = String.prototype.trim,

// Define a local copy of jQueryjQuery = function( selector, context ) {// The jQuery object is actually just the init constructor 'enhanced'return new jQuery.fn.init( selector, context, rootjQuery );},

// Used for matching numberscore_pnum = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,

// Used for detecting and trimming whitespacecore_rnotwhite = /\S/,core_rspace = /\s+/,

// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,

// A simple way to check for HTML strings// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,

// Match a standalone tagrsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,

Non-Minified JavaScript

Page 16: How I Learned to Stop Worrying and Love jQuery (Jan 2013)

(function(a,b){function G(a){var b=F[a]={};return p.each(a.split(s),function(a,c){b[c]=!0}),b}function J(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(I,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:+d+""===d?+d:H.test(d)?p.parseJSON(d):d}catch(f){}p.data(a,c,d)}else d=b}return d}function K(a){var b;for(b in a){if(b==="data"&&p.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function ba(){return!1}function bb(){return!0}function bh(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function bi(a,b){do a=a[b];while(a&&a.nodeType!==1);return a}function bj(a,b,c){b=b||0;if(p.isFunction(b))return p.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return p.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=p.grep(a,function(a){return a.nodeType===1});if(be.test(b))return p.filter(b,d,!c);b=p.filter(b,d)}return p.grep(a,function(a,d){return p.inArray(a,b)>=0===c})}function bk(a){var b=bl.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function bC(a,b){return a.getElementsByTagName(b)[0]||a.appendChild(a.ownerDocument.createElement(b))}function bD(a,b){if(b.nodeType!==1||!p.hasData(a))return;var c,d,e,f=p._data(a),g=p._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;d<e;d++)p.event.add(b,c,h[c][d])}g.data&&(g.data=p.extend({},g.data))}function bE(a,b){var c;if(b.nodeType!==1)return;b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase(),c==="object"?(b.parentNode&&(b.outerHTML=a.outerHTML),p.support.html5Clone&&a.innerHTML&&!p.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):c==="input"&&bv.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):c==="option"?b.selected=a.defaultSelected:c==="input"||c==="textarea"?b.defaultValue=a.defaultValue:c==="script"&&b.text!==a.text&&(b.text=a.text),b.removeAttribute(p.expando)}function bF(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bG(a){bv.test(a.type)&&(a.defaultChecked=a.checked)}function bY(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=bW.length;while(e--){b=bW[e]+c;if(b in a)return b}return d}function bZ(a,b){return a=b||a,p.css(a,"display")==="none"||!p.contains(a.ownerDocument,a)}function b$(a,b){var c,d,e=[],f=0,g=a.length;for(;f<g;f++){c=a[f];if(!c.style)continue;e[f]=p._data(c,"olddisplay"),b?(!e[f]&&c.style.display==="none"&&(c.style.display=""),c.style.display===""&&bZ(c)&&(e[f]=p._data(c,"olddisplay",cc(c.nodeName)))):(d=bH(c,"display"),!e[f]&&d!=="none"&&p._data(c,"olddisplay",d))}for(f=0;f<g;f++){c=a[f];if(!c.style)continue;if(!b||c.style.display==="none"||c.style.display==="")c.style.display=b?e[f]||"":"none"}return a}function b_(a,b,c){var d=bP.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function ca(a,b,c,d){var e=c===(d?"border":"content")?4:b==="width"?1:0,f=0;for(;e<4;e+=2)c==="margin"&&(f+=p.css(a,c+bV[e],!0)),d?(c==="content"&&(f-=parseFloat(bH(a,"padding"+bV[e]))||0),c!=="margin"&&(f-=parseFloat(bH(a,"border"+bV[e]+"Width"))||0)):(f+=parseFloat(bH(a,"padding"+bV[e]))||0,c!=="padding"&&(f+=parseFloat(bH(a,"border"+bV[e]+"Width"))||0));return f}function cb(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=!0,f=p.support.boxSizing&&p.css(a,"boxSizing")==="border-box";if(d<=0||d==null){d=bH(a,b);if(d<0||d==null)d=a.style[b];if(bQ.test(d))return d;e=f&&(p.support.boxSizingReliable||d===a.style[b]),d=parseFloat(d)||0}return d+ca(a,b,c||(f?"border":"content"),e)+"px"}function cc(a){if(bS[a])return bS[a];var b=p("<"+a+">").appendTo(e.body),c=b.css("display");b.remove();if(c==="none"||c===""){bI=e.body.appendChild(bI||p.extend(e.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!bJ||!bI.createElement)bJ=(bI.contentWindow||bI.contentDocument).document,bJ.write("<!doctype html><html><body>"),bJ.close();b=bJ.body.appendChild(bJ.createElement(a)),c=bH(b,"display"),e.body.removeChild(bI)}return bS[a]=c,c}

Minified JavaScript

Page 17: How I Learned to Stop Worrying and Love jQuery (Jan 2013)

Document Object Model (DOM)

Document

Head

Title Script

Body

Div

P

A

Div

UL

LI LI LI

<html> <head> <title>My Page</title> <script type="text/javascript“ src="http://code.jquery.com/jquery-1.7.1.min.js "> </script> </head> <body> <div> <p> This a <a href="Page2.htm">link</a> </p> </div> <div> Colors: <ul> <li>Red</li> <li>Orange</li> <li>Yellow</li> </ul> </div> </body></html>

Page 18: How I Learned to Stop Worrying and Love jQuery (Jan 2013)

Getting an Element

<script type="text/javaScript"> var id = "Div1"; var myDiv = document.GetElementById(id);</script>…<div id="Div1"> …</div>

Page 19: How I Learned to Stop Worrying and Love jQuery (Jan 2013)

Cross-Browser• Javascriptvar id = "Div1";var elm = null; if (document.getElementById) { elm = document.getElementById(id); } else if (document.all) { elm = document.all[id]; } else if (document.layers) { elm = document.layers[id]; }

• jQueryvar elm = $("#Div1");

Page 20: How I Learned to Stop Worrying and Love jQuery (Jan 2013)

jQuery Syntax

• jQuery keyword• Selectors• Events• Functions / Methods

Page 21: How I Learned to Stop Worrying and Love jQuery (Jan 2013)

“jQuery” Keyword

• jQuery• $• Represents the jQuery object• Indicates what follows is jQuery

Page 22: How I Learned to Stop Worrying and Love jQuery (Jan 2013)

Selectors

• Returns a set of objects• Call method on each object• Bind event to each object

Page 23: How I Learned to Stop Worrying and Love jQuery (Jan 2013)

CSS Selectorsh2 {

font-family: "Calibri";font-size: 66pt;font-weight: bold;

}.FootNote {

font-family: "Calibri";font-size: 18pt;font-weight: bold;

}#MyElement {

font-family: “Times New Roman";font-color: red;

}div#MyDiv {

font-family: “Arial";font-size: 48pt;

}

Tag name

Class name

Element ID

Combine selectors

Page 24: How I Learned to Stop Worrying and Love jQuery (Jan 2013)

jQuery Selectors

• $(selector)• where selector is:

Selector Select by… "#xxx" Id".xxx" className"xxx" element typexxx variable name

Example$("#MyDiv")$(".MyClass") $("a")$(document)

Page 25: How I Learned to Stop Worrying and Love jQuery (Jan 2013)

(document).ready

$(document).ready(function(){…

});

Page 26: How I Learned to Stop Worrying and Love jQuery (Jan 2013)

Events

$(document).ready(function(){ $("#MyDiv").click(function(){ … });});

Page 27: How I Learned to Stop Worrying and Love jQuery (Jan 2013)

Methods

$(document).ready(function(){ $(“#MyDiv”).click(function(){ $(“a”).attr(“target”, “_blank”); });});

Page 28: How I Learned to Stop Worrying and Love jQuery (Jan 2013)

Methods

$(document).ready(function(){ $(“#MyDiv”).click(function(){ $(“a”).attr(“target”, “_blank”); });});

Page 29: How I Learned to Stop Worrying and Love jQuery (Jan 2013)

Methods

$(function(){ $(“#MyDiv”).click(function(){ $(“a”).attr(“target”, “_blank”); });});

Page 30: How I Learned to Stop Worrying and Love jQuery (Jan 2013)

Combining Selectors

• Containership$(‘selector1 selector2’)Ex:

$(‘div a’)• Narrow scope

$(‘Selector1Selector2’)Ex:

$(‘a#MyLink’)

Page 31: How I Learned to Stop Worrying and Love jQuery (Jan 2013)

Set-based Selectors

• $("div:first")• $("div:last")• $("div:even")• $("div:odd")

Page 32: How I Learned to Stop Worrying and Love jQuery (Jan 2013)

Ajax

• Call web service from jQuery

Page 33: How I Learned to Stop Worrying and Love jQuery (Jan 2013)

Ajax

$.ajax({ url: "CustomerWs.asmx/GetCustomerName", dataType: "text", type: "POST", data: {}, error: function (err) { // Code to run when error returned }, success: function (data) { // Code to run when successfully returned }

Page 34: How I Learned to Stop Worrying and Love jQuery (Jan 2013)

Plug-Ins

• jQuery is extensible!• jQueryUI

Page 35: How I Learned to Stop Worrying and Love jQuery (Jan 2013)

jQuery UI

Page 36: How I Learned to Stop Worrying and Love jQuery (Jan 2013)

Help!

• docs.jquery.com• api.jquery.com• jqueryui.com/demos

Page 38: How I Learned to Stop Worrying and Love jQuery (Jan 2013)

David Giard

• DavidGiard.com• TechnologyAndFriends.com• @DavidGiard.com

Page 39: How I Learned to Stop Worrying and Love jQuery (Jan 2013)