35
2009 Mats Bryntse

jQuery with javascript training by Technnovation Labs

Embed Size (px)

DESCRIPTION

At TLabs, we respect the demand of time & love to go along with it. Acknowledging the trends we serve neatly designed syllabus that explores jQuery covering the thorough fundamentals of JavaScript. Having a basic knowledge of JavaScript will go a long way in understanding, structuring, and debugging your code. After the completion of this course, you will be able to create plug-ins on top of the JavaScript library to create abstractions for low-level interaction and animation, advanced effects and high-level, theme-able widgets. The modular approach to the jQuery library allows the creation of powerful dynamic web pages and web applications as well.

Citation preview

Page 1: jQuery with javascript training by Technnovation Labs

2009 Mats Bryntse

Page 2: jQuery with javascript training by Technnovation Labs

Contents What is JavaScript JavaScript Basics Functions Objects Bad parts Prototype Scope Ajax JSON Debugging Tools Performance Events Error handling Future of JavaScript

Page 3: jQuery with javascript training by Technnovation Labs

What is JavaScript

ECMAScript Current version in browsers is ECMA-262 edition 3, 3.1 to be finalized in December

2009 http://www.ecma-international.org Not tied to web browsers

DOM – Document object model API for working with XML/HTML, 3 levels (level 1 became W3C recommendation in October 1998) http://www.w3.org/DOM/

BOM (Browser object model) navigator, location, screen, XMLHttpRequest, ActiveXObject... No backing standard

ECMAScript

DOM BOM

JavaScript

- The worlds most popular programming language..?

Page 4: jQuery with javascript training by Technnovation Labs

JavaScript overviewJavaScript is a class-free, object-oriented languageDynamic language, you can change any object at any

timePrototypal inheritance (inherit from objects)Lamda functions (or ’anonymous’ functions)5 primitive types:

number string boolean null undefined

Loosely typed language var a = 2;a === "2" // falsea = "2"; // a is now a stringa === "2" // true

Page 5: jQuery with javascript training by Technnovation Labs

FunctionsFunctions are first class objects

var Cat = function () { // This is called a constructor function this.purr = function() {};}

Create instance: use the new keywordvar myCat = new Cat(); typeof(myCat) // ”object”, not very intuitivemyCat instanceof Cat // true, instanceof gives the expected answer

// Watch out when forgetting the new operatorvar cat = Cat();window.purr // window object is now clobbered

Function arguments available through arguments

function myFunc() {return arguments.length;

}myFunc(”a”, ”b”, ”c”); // returns 3

Page 6: jQuery with javascript training by Technnovation Labs

Objects and arrays Everything that is not a primitive derives from Object

window.toString instanceof Object // = true Objects are associative arrays / hashtables

var a = { text : 'test'};a["text"] == a.text // true

Testing for object property”text” in a // true

Enumerating object propertiesfor (var o in window) { console.log(o + ':' + window[o]);}

Array basics push : adds an element length concat : join 2 arrays join(string) : string represenation of the array split by the argument slice(start, end) : returns elements between args sort ([function]) : sorts by alphabet or by function supplied as arg pop : extracts last element

Page 7: jQuery with javascript training by Technnovation Labs

Some bad partsGlobal variables

window object is shared by everyoneno warning or crash if a variable is overwritten Easy to end-up with ”function soup”, an unmaintainable

mess of global objects & functions (MS Virtual Earth)eval & with

var o = {};with (o) { prop = 2; // prop isn’t defined on object o and ends up on the global object}alert(prop); // 2

== & !=typeofsemi-colon insertion0.1 + 0.2 == 0.3 // false (IEEE 754 floating point)

Page 8: jQuery with javascript training by Technnovation Labs

PrototypeEvery function has a prototype, a shared object

var sword = function() { this.swing = function(){ // Every sword instance will have its own version of

swing console.log(”Swing”); };};

var sword = function() {};

sword.prototype.swing = function(){ // Every sword created will share this function

console.log(”Swing”);};

Use hasOwnProperty to distinguish prototype methods from own properties

Page 9: jQuery with javascript training by Technnovation Labs

Execution ScopeScope is the execution context, the this property

var obj = { number : 42, showNumber: function () { alert(this.number); }}; obj.showNumber(); // 42

document.body.onclick = obj.showNumber; // clicking the body shows ”undefined”

call and apply can bind a new scope to a functionvar anotherObj = { number : ”blablabla” };obj.showNumber.call(anotherObj); // ”blablabla”

call (scope, arg1, arg2, ...) apply(scope, [arg1, arg2, ...])

Variable scope: function scope, not block scopefor(var i = 0; i<5;i++) {}alert(i); // 5

Page 10: jQuery with javascript training by Technnovation Labs

Asynchronous JavaScript and XMLTerm coined by Jesse James Garret in 2005XHR added in IE5 through an ActiveX objectAll browsers (IE7+) supports the

XMLHttpRequest objectCross domain restrictions applyIE8 implements XDomainRequests, (does

not send cookies)

Page 11: jQuery with javascript training by Technnovation Labs

JSONJavaScript Object NotationInvented by Douglas Crockford of YahooThe preferred data transfer format of the webMore lightweight than XML{ ”property” : ”value”}

Possible value types: String Number Object Array true false null

eval the JSON to get a native JS object, or use a JSON parser. ECMAScript 3.1 will have native support for JSON.parse and JSON.stringify (already in FF3.1)

Page 12: jQuery with javascript training by Technnovation Labs

DebuggingFireBug for Firefox(Lite for IE) (1.4 adds JSON

viewer)Fiddler (if using http://localhost, use

http://localhost.) JsonViewer plugin SyntaxViewer plugin

IE: Internet Options -> Advanced -> Disable script debugging

debugger; attaches a client-side debuggerIE8 has a developer toolbar builtin, for previous

versions there is IE Developer Toolbar

Page 13: jQuery with javascript training by Technnovation Labs

Tools Validators

JsLint JavaScriptLint

Minifiers JsMin Dojo ShrinkSafe YUI Compressor

Unit testing JsUnit YUI Test Dojo Object Harness

Documentation generators JsDoc YUI Doc

Secure execution environments ADSafe (Crockford) Caja

Page 14: jQuery with javascript training by Technnovation Labs

Performance YUI Exceptional Performance Team Use Yslow plugin to FB If using namespaced objects repeatedly, assign to a local variable first

BADmyNS.subNS.obj.prop = 2;myNS.subNS.obj.name = ”Test”;myNS.subNS.obj.index = 2345;

BETTERvar m = myNS.subNS.obj;m.prop = 2;m.name ....

Even if the JavaScript engines ran at infinite speed, web pages would not run noticeably faster. The DOM operations are typically the culprit when it comes to poor performance.

Read Steve Souders blog on High performance websites

Page 15: jQuery with javascript training by Technnovation Labs

EventsEvents handling in the DOM is tricky, browser

implementations vary. Using a JS library that normalizes the event

object is very helpfulRegistering events the old fashioned way (DOM

level 0) <a href="http://www.facebook.com” onclick="return

fbs_click(this)">Facebook</a> element.onclick = function() {} Only one listener can be registered, last listener assigned wins

”Correct” way of doing this W3C : element.addEventListener(’click’, fn, [executeInCapturePhase]) IE : element.attachEvent('onclick', fn) // flawed (this points to window in

fn, useless)

Page 16: jQuery with javascript training by Technnovation Labs

Introduce jQuery

Page 17: jQuery with javascript training by Technnovation Labs

jQuery

• Cross-browser javascript library• Free & Opensource• First released Jan 06 @Barcamp by John Resig• Last stable version 1.10.2

Page 18: jQuery with javascript training by Technnovation Labs

Why jQuery ?• Cross-browser compatibility• Fast & Small • Plug-in• Learning curve & Documentation• Intellisense in VS2008-2010• Microsoft [Ajax Lib & MVC]

Page 19: jQuery with javascript training by Technnovation Labs

Why jQuery ?

Page 20: jQuery with javascript training by Technnovation Labs

Who’s using jQuery

• Microsoft• Google• Mozilla• Digg• Wordpress & Drupal• HP - IBM - Intel.• Ruby on Rails

Page 21: jQuery with javascript training by Technnovation Labs

Getting Start

• Download jQuery at jquery.com– <script type="text/javascript" src="/js/jQuery. js"></script>

• Microsoft CDN or Google CDN– <script src="http://ajax.microsoft.com/ajax/jquery/jquery-

1.4.2.js" type="text/javascript"></script>– <script type="text/javascript"

src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.js"></script>

Page 22: jQuery with javascript training by Technnovation Labs

Hello world jQuery

• Document ready

$(document).ready(function () { alert("Hello world jQuery");});

// Short cut$(function () { alert("Hello world jQuery");});

Page 23: jQuery with javascript training by Technnovation Labs

jQuery Philosophy

Find someone

from HTML(selector)

Do something

to it(method)

Page 24: jQuery with javascript training by Technnovation Labs

Find some element

Page 25: jQuery with javascript training by Technnovation Labs

Selector

• CSS Style– $(“#myID”) // by id– $(“.myClass”) // by class name– $(“myTag”) // by tag (element name)– $(“#id, .class, tag”) // multiple

Page 26: jQuery with javascript training by Technnovation Labs

Selector [Hierarchy]• $("form input") // descendant• $("#main > *") // child• $("#prev ~ div") // sibling

Page 27: jQuery with javascript training by Technnovation Labs

Selector [Hierarchy]• $("form input") // descendant

<form> <div> Form is surrounded by the green outline</div> <label> Child:</label> <input name="name" /> <fieldset> <label> Grandchild:</label> <input name="newsletter" /> </fieldset></form>

Page 28: jQuery with javascript training by Technnovation Labs

Selector [Attribute]

• $("div[id]"). //has• $("input[name='bank']“) //not has• $("input[name^='news']") //equal• $("input[name$='letter']") //begin with• $("input[name$='letter']") //end with• $("input[name*='man']") //contain• $("input[id][name$='man']")

Page 29: jQuery with javascript training by Technnovation Labs

Selector [Form]

• $("div :text")• $("form :radio")• $("#dvMainForm :checkbox")• $(":button")• $("input:disabled")• $("input:checked")

Page 30: jQuery with javascript training by Technnovation Labs

Do something with them

Page 31: jQuery with javascript training by Technnovation Labs

Attribute• $("em").attr("title")• $("label").html()• $("p:first").text()• $("input").val()

• $("em").attr("title", "zupzip")• $("label").html("zupzip")• $("p:first").text("zupzip")• $("input").val("zupzip")

Get

Set

Page 32: jQuery with javascript training by Technnovation Labs

Event• Bind– $(“input”).bind(“blur”, fn);

• Trigger– $(“input”).trigger(“focus”);

• Event Helper– $(“input”).click(function() { alert(‘click’); });– S(“input”).click();

• Live– $(“input”).live(“click”, fn);

Page 33: jQuery with javascript training by Technnovation Labs

Traversing• find $("p").find("span").css('color','red'); • children $("div").children(".selected").css("color); • parent $("tr").parent().get(0).tagName;• next $("button[disabled]").next().text("this

button is disabled"); • prev $("p").prev(".selected").css("background",

"yellow");• sibling $(".hilite").siblings() .css("color", "red")

Page 34: jQuery with javascript training by Technnovation Labs

Manipulation

• append $("p").append("<strong>Hello</strong>");

• appendTo $("span").appendTo("#foo");• prepend &prependTo• after $("p").after("<b>Hello</b>"); • before $("p").before("<b>Hello</b>");

Page 35: jQuery with javascript training by Technnovation Labs

Effect

• show / hide• toggle• slide• fade• Custom animation