SlideShare a Scribd company logo
2009 Mats Bryntse
Contents
 What is JavaScript
 JavaScript Basics
 Functions
 Objects
 Bad parts
 Prototype
 Scope
 Ajax
 JSON
 Debugging
 Tools
 Performance
 Events
 Error handling
 Future of JavaScript
What is JavaScript
- The worlds most popular programming language..?

JavaScript
ECMAScript

DOM

BOM

 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
JavaScript overview
 JavaScript is a class-free, object-oriented language
 Dynamic language, you can change any object at any time
 Prototypal 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" // false
a = "2"; // a is now a string
a === "2" // true
Functions
Functions are first class objects

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

Create instance: use the new keyword
var myCat = new Cat();
typeof(myCat) // ”object”, not very intuitive
myCat instanceof Cat // true, instanceof gives the expected answer
// Watch out when forgetting the new operator
var 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
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 properties

for (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
Some bad parts
Global variables

 window object is shared by everyone
 no 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

== & !=
typeof
semi-colon insertion
0.1 + 0.2 == 0.3 // false (IEEE 754 floating point)
Prototype
Every function has a prototype, a shared object
var sword = function() {
this.swing = function(){
console.log(”Swing”);
};
};

// Every sword instance will have its own version of 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
Execution Scope
Scope 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 function
var anotherObj = { number : ”blablabla” };
obj.showNumber.call(anotherObj); // ”blablabla”

 call (scope, arg1, arg2, ...)

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

Variable scope: function scope, not block scope
for(var i = 0; i<5;i++) {}
alert(i); // 5
Asynchronous JavaScript and XML
Term coined by Jesse James Garret in 2005
XHR added in IE5 through an ActiveX object
All browsers (IE7+) supports the

XMLHttpRequest object
Cross domain restrictions apply
IE8 implements XDomainRequests, (does not
send cookies)
JSON
 JavaScript Object Notation
 Invented by Douglas Crockford of Yahoo
 The preferred data transfer format of the web
 More 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)
Debugging
FireBug 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 debugger
IE8 has a developer toolbar builtin, for previous versions
there is IE Developer Toolbar
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
Performance
 YUI Exceptional Performance Team
 Use Yslow plugin to FB
 If using namespaced objects repeatedly, assign to a local variable first
BAD
myNS.subNS.obj.prop = 2;
myNS.subNS.obj.name = ”Test”;
myNS.subNS.obj.index = 2345;
BETTER
var 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
Events
Events handling in the DOM is tricky, browser

implementations vary.
Using a JS library that normalizes the event object is
very helpful
Registering 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)
Introduce jQuery
jQuery
•
•
•
•

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

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

Microsoft
Google
Mozilla
Digg
Wordpress & Drupal
HP - IBM - Intel.
Ruby on Rails
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/jquery1.4.2.js" type="text/javascript"></script>
– <script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jq
uery.js"></script>
Hello world jQuery
• Document ready
$(document).ready(function () {
alert("Hello world jQuery");
});
// Short cut
$(function () {
alert("Hello world jQuery");
});
jQuery Philosophy

Find
someone
from HTML
(selector)

Do
something
to it
(method)
Find some element
Selector
• CSS Style
– $(“#myID”)
// by id
– $(“.myClass”)
// by class name
– $(“myTag”)
// by tag (element name)
– $(“#id, .class, tag”) // multiple
Selector [Hierarchy]
• $("form input")
// descendant
• $("#main > *")// child
• $("#prev ~ div")
// sibling
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>
Selector [Attribute]
•
•
•
•
•
•
•

$("div[id]").
$("input[name='bank']“)
$("input[name^='news']")
$("input[name$='letter']")
$("input[name$='letter']")
$("input[name*='man']")
$("input[id][name$='man']")

//has
//not has
//equal
//begin with
//end with
//contain
Selector [Form]
•
•
•
•
•
•

$("div :text")
$("form :radio")
$("#dvMainForm :checkbox")
$(":button")
$("input:disabled")
$("input:checked")
Do something with them
Attribute
•
•
•
•

$("em").attr("title")
$("label").html()
Get
$("p:first").text()
$("input").val()
• $("em").attr("title", "zupzip")
• $("label").html("zupzip")
Set
• $("p:first").text("zupzip")
• $("input").val("zupzip")
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);
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")
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>");
Effect
•
•
•
•
•

show / hide
toggle
slide
fade
Custom animation

More Related Content

PPT
The Theory Of The Dom
kaven yan
 
PDF
JavaScript Library Overview
jeresig
 
PDF
Javascript Best Practices
Christian Heilmann
 
PDF
JavaScript Best Pratices
ChengHui Weng
 
PDF
From YUI3 to K2
kaven yan
 
PDF
Bytecode manipulation with Javassist and ASM
ashleypuls
 
PDF
JavaScript - From Birth To Closure
Robert Nyman
 
PDF
Maintainable JavaScript 2011
Nicholas Zakas
 
The Theory Of The Dom
kaven yan
 
JavaScript Library Overview
jeresig
 
Javascript Best Practices
Christian Heilmann
 
JavaScript Best Pratices
ChengHui Weng
 
From YUI3 to K2
kaven yan
 
Bytecode manipulation with Javassist and ASM
ashleypuls
 
JavaScript - From Birth To Closure
Robert Nyman
 
Maintainable JavaScript 2011
Nicholas Zakas
 

What's hot (20)

PDF
Inside the JVM - Follow the white rabbit!
Sylvain Wallez
 
PDF
JavaScript in 2016
Codemotion
 
PPTX
Scripting as a Second Language
Rob Dunn
 
PDF
JavaScript Good Practices
Jussi Pohjolainen
 
PPTX
Making Java more dynamic: runtime code generation for the JVM
Rafael Winterhalter
 
PDF
Developing Useful APIs
Dmitry Buzdin
 
PDF
A Practitioner’s guide to Hardened JavaScript
Tom Van Cutsem
 
PDF
Secrets of JavaScript Libraries
jeresig
 
PDF
Patterns for JVM languages - Geecon 2014
Jaroslaw Palka
 
PPTX
JS Event Loop
Saai Vignesh P
 
ODP
From object oriented to functional domain modeling
Codemotion
 
PPT
"Scala in Goozy", Alexey Zlobin
Vasil Remeniuk
 
PDF
Performance Optimization and JavaScript Best Practices
Doris Chen
 
PDF
Tornadoweb
Osman Yuksel
 
PDF
7 Sins of Java fixed in Kotlin
Luca Guadagnini
 
PPTX
Async task, threads, pools, and executors oh my!
Stacy Devino
 
KEY
JavaOne 2011 - JVM Bytecode for Dummies
Charles Nutter
 
PDF
Prototype
Aditya Gaur
 
PPTX
Javascript Prototype Visualized
军 沈
 
PDF
Mobile Open Day: React Native: Crossplatform fast dive
epamspb
 
Inside the JVM - Follow the white rabbit!
Sylvain Wallez
 
JavaScript in 2016
Codemotion
 
Scripting as a Second Language
Rob Dunn
 
JavaScript Good Practices
Jussi Pohjolainen
 
Making Java more dynamic: runtime code generation for the JVM
Rafael Winterhalter
 
Developing Useful APIs
Dmitry Buzdin
 
A Practitioner’s guide to Hardened JavaScript
Tom Van Cutsem
 
Secrets of JavaScript Libraries
jeresig
 
Patterns for JVM languages - Geecon 2014
Jaroslaw Palka
 
JS Event Loop
Saai Vignesh P
 
From object oriented to functional domain modeling
Codemotion
 
"Scala in Goozy", Alexey Zlobin
Vasil Remeniuk
 
Performance Optimization and JavaScript Best Practices
Doris Chen
 
Tornadoweb
Osman Yuksel
 
7 Sins of Java fixed in Kotlin
Luca Guadagnini
 
Async task, threads, pools, and executors oh my!
Stacy Devino
 
JavaOne 2011 - JVM Bytecode for Dummies
Charles Nutter
 
Prototype
Aditya Gaur
 
Javascript Prototype Visualized
军 沈
 
Mobile Open Day: React Native: Crossplatform fast dive
epamspb
 
Ad

Viewers also liked (20)

PPTX
HTML, CSS, JS & Jquery Introduction
Islam AlZatary
 
PPT
20121228 jqueryui - button - By Nat
LearningTech
 
KEY
jQueryUI
Larry Ball
 
PPTX
Cartegraph Live HTML, CSS, JavaScript and jQuery Training
Shane Church
 
PDF
Javascript jQuery jQuery Ui
Tom Friedhof
 
PPTX
PostgreSQL Database Slides
metsarin
 
DOCX
PHP HTML CSS Notes
Tushar Rajput
 
PPTX
HTML CSS and Web Development
Rahul Mishra
 
PDF
HTML CSS JavaScript jQuery Training
ubshreenath
 
PPTX
JavaScript and jQuery Basics
Kaloyan Kosev
 
PDF
Surveying for Widening of the Road Segment 28 Kilo to Kathmandu University
Upendra Oli
 
PDF
JavaScript Basics And DOM Manipulation
Siarhei Barysiuk
 
PDF
jQuery UI and Plugins
Marc Grabanski
 
ODP
Mapserver vs. geoserver
鸣 饶
 
PPTX
jQuery from the very beginning
Anis Ahmad
 
ODP
PostgreSQL Administration for System Administrators
Command Prompt., Inc
 
PDF
HTML CSS Basics
Mai Moustafa
 
PDF
Introduction to PHP
Bradley Holt
 
ODP
OpenGurukul : Database : PostgreSQL
Open Gurukul
 
PDF
Postgresql database administration volume 1
Federico Campoli
 
HTML, CSS, JS & Jquery Introduction
Islam AlZatary
 
20121228 jqueryui - button - By Nat
LearningTech
 
jQueryUI
Larry Ball
 
Cartegraph Live HTML, CSS, JavaScript and jQuery Training
Shane Church
 
Javascript jQuery jQuery Ui
Tom Friedhof
 
PostgreSQL Database Slides
metsarin
 
PHP HTML CSS Notes
Tushar Rajput
 
HTML CSS and Web Development
Rahul Mishra
 
HTML CSS JavaScript jQuery Training
ubshreenath
 
JavaScript and jQuery Basics
Kaloyan Kosev
 
Surveying for Widening of the Road Segment 28 Kilo to Kathmandu University
Upendra Oli
 
JavaScript Basics And DOM Manipulation
Siarhei Barysiuk
 
jQuery UI and Plugins
Marc Grabanski
 
Mapserver vs. geoserver
鸣 饶
 
jQuery from the very beginning
Anis Ahmad
 
PostgreSQL Administration for System Administrators
Command Prompt., Inc
 
HTML CSS Basics
Mai Moustafa
 
Introduction to PHP
Bradley Holt
 
OpenGurukul : Database : PostgreSQL
Open Gurukul
 
Postgresql database administration volume 1
Federico Campoli
 
Ad

Similar to jQuery with javascript training by Technnovation Labs (20)

PPTX
All of Javascript
Togakangaroo
 
PPT
JavaScript Basics
Mats Bryntse
 
PPTX
UNIT 1 (7).pptx
DrDhivyaaCRAssistant
 
PPT
Introduction to Javascript
Amit Tyagi
 
PDF
Wt unit 2 ppts client sied technology
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
PDF
Wt unit 2 ppts client side technology
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
KEY
JavaScript Neednt Hurt - JavaBin talk
Thomas Kjeldahl Nilsson
 
PPT
lecture 6 javascript event and event handling.ppt
ULADATZ
 
PPT
JavaScript Misunderstood
Bhavya Siddappa
 
PPTX
All of javascript
Togakangaroo
 
PPT
Reversing JavaScript
Roberto Suggi Liverani
 
PDF
Basics of JavaScript
Bala Narayanan
 
PDF
AJS UNIT-1 2021-converted.pdf
SreeVani74
 
PDF
Javascript: the important bits
Chris Saylor
 
PPTX
Java scriptforjavadev part2a
Makarand Bhatambarekar
 
PPTX
Java script
Adrian Caetano
 
PPTX
Learning About JavaScript (…and its little buddy, JQuery!)
Julie Meloni
 
PPT
JavaScript - An Introduction
Manvendra Singh
 
PPTX
javaScript and jQuery
Mehrab Hossain
 
All of Javascript
Togakangaroo
 
JavaScript Basics
Mats Bryntse
 
UNIT 1 (7).pptx
DrDhivyaaCRAssistant
 
Introduction to Javascript
Amit Tyagi
 
Wt unit 2 ppts client sied technology
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
Wt unit 2 ppts client side technology
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
JavaScript Neednt Hurt - JavaBin talk
Thomas Kjeldahl Nilsson
 
lecture 6 javascript event and event handling.ppt
ULADATZ
 
JavaScript Misunderstood
Bhavya Siddappa
 
All of javascript
Togakangaroo
 
Reversing JavaScript
Roberto Suggi Liverani
 
Basics of JavaScript
Bala Narayanan
 
AJS UNIT-1 2021-converted.pdf
SreeVani74
 
Javascript: the important bits
Chris Saylor
 
Java scriptforjavadev part2a
Makarand Bhatambarekar
 
Java script
Adrian Caetano
 
Learning About JavaScript (…and its little buddy, JQuery!)
Julie Meloni
 
JavaScript - An Introduction
Manvendra Singh
 
javaScript and jQuery
Mehrab Hossain
 

More from Prasad Shende (10)

PPTX
Domain strength
Prasad Shende
 
PPTX
Internship mca mcs mcm 6 1-15 [autosaved]
Prasad Shende
 
PPTX
Internship mca mcs mcm 6 1-15 [autosaved]
Prasad Shende
 
PPTX
Internship mca mcs mcm 6 1-15 [autosaved]
Prasad Shende
 
PDF
On Job Training Program
Prasad Shende
 
PPTX
Front-end Development Training by Technnovation Labs
Prasad Shende
 
PPTX
Web Design Training in Pune by Technnovation Labs
Prasad Shende
 
PPTX
HTML5 Training in Pune by Technnovation Labs
Prasad Shende
 
PPTX
Wordpress Training in Pune by Technnovation Labs
Prasad Shende
 
PPTX
Drupal Training by Technnovation Labs
Prasad Shende
 
Domain strength
Prasad Shende
 
Internship mca mcs mcm 6 1-15 [autosaved]
Prasad Shende
 
Internship mca mcs mcm 6 1-15 [autosaved]
Prasad Shende
 
Internship mca mcs mcm 6 1-15 [autosaved]
Prasad Shende
 
On Job Training Program
Prasad Shende
 
Front-end Development Training by Technnovation Labs
Prasad Shende
 
Web Design Training in Pune by Technnovation Labs
Prasad Shende
 
HTML5 Training in Pune by Technnovation Labs
Prasad Shende
 
Wordpress Training in Pune by Technnovation Labs
Prasad Shende
 
Drupal Training by Technnovation Labs
Prasad Shende
 

Recently uploaded (20)

PDF
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
PPTX
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
PDF
Beyond Automation: The Role of IoT Sensor Integration in Next-Gen Industries
Rejig Digital
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
PPTX
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
PPTX
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PDF
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
PDF
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
PDF
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
PDF
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
PDF
This slide provides an overview Technology
mineshkharadi333
 
PDF
Doc9.....................................
SofiaCollazos
 
PDF
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
PPTX
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
PPTX
IoT Sensor Integration 2025 Powering Smart Tech and Industrial Automation.pptx
Rejig Digital
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PDF
Architecture of the Future (09152021)
EdwardMeyman
 
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
Dev Dives: Automate, test, and deploy in one place—with Unified Developer Exp...
AndreeaTom
 
Beyond Automation: The Role of IoT Sensor Integration in Next-Gen Industries
Rejig Digital
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
OA presentation.pptx OA presentation.pptx
pateldhruv002338
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
SparkLabs Primer on Artificial Intelligence 2025
SparkLabs Group
 
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
Automating ArcGIS Content Discovery with FME: A Real World Use Case
Safe Software
 
This slide provides an overview Technology
mineshkharadi333
 
Doc9.....................................
SofiaCollazos
 
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
IoT Sensor Integration 2025 Powering Smart Tech and Industrial Automation.pptx
Rejig Digital
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
Architecture of the Future (09152021)
EdwardMeyman
 

jQuery with javascript training by Technnovation Labs

  • 2. Contents  What is JavaScript  JavaScript Basics  Functions  Objects  Bad parts  Prototype  Scope  Ajax  JSON  Debugging  Tools  Performance  Events  Error handling  Future of JavaScript
  • 3. What is JavaScript - The worlds most popular programming language..? JavaScript ECMAScript DOM BOM  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
  • 4. JavaScript overview  JavaScript is a class-free, object-oriented language  Dynamic language, you can change any object at any time  Prototypal 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" // false a = "2"; // a is now a string a === "2" // true
  • 5. Functions Functions are first class objects var Cat = function () { // This is called a constructor function this.purr = function() {}; } Create instance: use the new keyword var myCat = new Cat(); typeof(myCat) // ”object”, not very intuitive myCat instanceof Cat // true, instanceof gives the expected answer // Watch out when forgetting the new operator var 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
  • 6. 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 properties for (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
  • 7. Some bad parts Global variables  window object is shared by everyone  no 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 == & != typeof semi-colon insertion 0.1 + 0.2 == 0.3 // false (IEEE 754 floating point)
  • 8. Prototype Every function has a prototype, a shared object var sword = function() { this.swing = function(){ console.log(”Swing”); }; }; // Every sword instance will have its own version of 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
  • 9. Execution Scope Scope 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 function var anotherObj = { number : ”blablabla” }; obj.showNumber.call(anotherObj); // ”blablabla”  call (scope, arg1, arg2, ...) apply(scope, [arg1, arg2, ...]) Variable scope: function scope, not block scope for(var i = 0; i<5;i++) {} alert(i); // 5
  • 10. Asynchronous JavaScript and XML Term coined by Jesse James Garret in 2005 XHR added in IE5 through an ActiveX object All browsers (IE7+) supports the XMLHttpRequest object Cross domain restrictions apply IE8 implements XDomainRequests, (does not send cookies)
  • 11. JSON  JavaScript Object Notation  Invented by Douglas Crockford of Yahoo  The preferred data transfer format of the web  More 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)
  • 12. Debugging FireBug 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 debugger IE8 has a developer toolbar builtin, for previous versions there is IE Developer Toolbar
  • 13. 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
  • 14. Performance  YUI Exceptional Performance Team  Use Yslow plugin to FB  If using namespaced objects repeatedly, assign to a local variable first BAD myNS.subNS.obj.prop = 2; myNS.subNS.obj.name = ”Test”; myNS.subNS.obj.index = 2345; BETTER var 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
  • 15. Events Events handling in the DOM is tricky, browser implementations vary. Using a JS library that normalizes the event object is very helpful Registering 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)
  • 17. jQuery • • • • Cross-browser javascript library Free & Opensource First released Jan 06 @Barcamp by John Resig Last stable version 1.10.2
  • 18. Why jQuery ? • • • • • • Cross-browser compatibility Fast & Small Plug-in Learning curve & Documentation Intellisense in VS2008-2010 Microsoft [Ajax Lib & MVC]
  • 21. 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/jquery1.4.2.js" type="text/javascript"></script> – <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jq uery.js"></script>
  • 22. Hello world jQuery • Document ready $(document).ready(function () { alert("Hello world jQuery"); }); // Short cut $(function () { alert("Hello world jQuery"); });
  • 25. Selector • CSS Style – $(“#myID”) // by id – $(“.myClass”) // by class name – $(“myTag”) // by tag (element name) – $(“#id, .class, tag”) // multiple
  • 26. Selector [Hierarchy] • $("form input") // descendant • $("#main > *")// child • $("#prev ~ div") // sibling
  • 27. 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>
  • 29. Selector [Form] • • • • • • $("div :text") $("form :radio") $("#dvMainForm :checkbox") $(":button") $("input:disabled") $("input:checked")
  • 32. 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);
  • 33. 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")
  • 34. 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>");