SlideShare a Scribd company logo
1 of 98
JavaScript is a lightweight programming
language to add interactivity to HTML
pages.
 Put

dynamic text into an HTML page.
 React to events
 Read and write HTML elements
 Validate input data
 Detect the visitor's browser
 Create cookies
New in Html 5:
 Access new HTML Elements and Events.
 Draw using canvas object
 Geolocation: get current location position.
 Offline Storage
 Post message
 Multiple Thread
 Socket Programming
 Offline web application
 Embedded

in Html.

<script type="text/javascript"><![CDATA[
JavaScript Code
]]></script>

 Scripts

can be provided locally or remotely.

<script language="JavaScript” type="text/javascript“
src="http://somesite/myOwnJavaScript.js">
</script>
 Variable

scope and declaration.
 Popup Boxes:
alert("sometext")
confirm("sometext")
prompt("sometext","defaultvalue")
 Conditional

statement

• if, if.. else, switch
 Loop

• for loop, while loop
 try...catch
 Throw
 Encapsulate

your code into functions
 Common

Features

• DOM Selector
• DOM modification
• Traversing

• Dynamic Styles
• Events
Compatibility Items:
 Elements
 Attributes
 Browser version
 Device/Operating system
Detect the visitor's browser
var x = "User-agent header sent: " + navigator.userAgent;
User-agent header sent: Opera/9.80 (Windows NT 5.1)
Presto/2.12.388 Version/12.16
var el = document.createElement(“new_el”);
element.appendChild(el);

document.body.appendChild(el);
var fragment = document.createDocumentFragment ();
fragment.appendChild(el_1)
fragment.appendChild(el_2)
fragment.appendChild(el_3)
fragment.appendChild(el_4)

document.body.appendChild(fragment);
var el = document.getElementById(„Id‟);//single element
if (document.all || document.getElementById) {
...
}
val el = document.get ElementsByClassName(„el‟);//select collection of nodes
el[0] //get the first element
val el = document.get ElementsByTagName(„tagName‟);//select collection of
nodes
el[0] //get the first element
val el = document.get ElementsByTagName(„*‟);//select all tags
val el = document.get ElementsByName(„el‟);//select collection of nodes
el[0] //get the first element
var el = document.querySelector(„#Id‟);//select first element
val el = document.querySelector( „.el‟);//select first element
val el = document.querySelectorAll( „.el‟);//select collection of nodes
 Some

old:

• getElementById
• getElementsByTagNameNot work with object
 Some

new:

• getElementsByClassName
 Firefox 3, Safari 3, Opera 9.6, IE9
 Opera doesn’t match a second-specified class
• querySelectorAll
 In Firefox 3.1, Safari 3.1, Opera 10, IE 8
 Safari 3.1 had memory out of bounds problems
 Safari 3.2 can’t match uppercase characters in quirks mode
DOM Collection

links
document.links
document.links[0]

forms

document.forms
document.forms[0]

anchors

document.anhors
document. anhors[0]
element.innerHTML = “HTML code”;
var attributeValue = element.getAttribute(attributeName);
element.setAttribute(attributeName, attributeValue);
element.removeChild(el1);
var el = element.parentNode;
var el = element.childNodes; //Elements + White space
var el = element.children; //Only Elements
var el = element..nextSibling; //next node or null
var el = element..previousSibling; //previous node or null
var el = element..nextElementSibling;
var el = element..previousElementSibling;
 onabort

- Loading of an image is interrupted
 onblur - An element loses focus
 onchange - The content of a field changes
 onclick - Mouse clicks an object
 ondblclick - Mouse double-clicks an object
 onerror - An error occurs when loading a
document or an image
 onfocus - An element gets focus
 onkeydown - A keyboard key is pressed
 onkeypress

- A keyboard key is pressed or

held down
 onkeyup - A keyboard key is released
 onload - A page or an image is finished
loading
 onmousedown - A mouse button is pressed
 onmousemove - The mouse is moved
 onmouseout - The mouse is moved off an
element
 onmouseover - The mouse is moved over an
element
 onmouseup - A mouse button is released
 onreset

- The reset button is clicked
 onresize A window or frame is resized
 onselect - Text is selected
 onsubmit - The submit button is clicked
 onunload - The user exits the page
<img id="myImage"
src="http://3.bp.blogspot.com/_ss1KeGx9Bng/THgWaTaHhuI/AAAAAAAAAB0/3PL
mvniAdNk/s1600/lolcats_oh-noes_ihasletgo.jpg">
<script>
var img = document.getElementById("myImage"),
img2=new Image(),
originalSrc = img.src;

img2.src="https://i.chzbgr.com/maxW500/6073452544/h4B353A81/";
img.onmouseover = function(){
document.getElementById('myImage').src=img2.src;
}

img.onmouseout = function(){
document.getElementById('myImage').src=originalSrc;
}
</script>
// Internet Explorer
element.attachEvent('click',
function() {
alert(window.event);
}
)
// Everyone else
element.addEventListener('click',
function(ev) { alert(ev) }, false
);




Bubbling: the event is first captured and handled by the inner most
element and then propagated to outer elements.
Capturing : event is first captured by the outer most element and
propagated to the inner most element.
Only event bubbling model is supported by all the major browsers.

if ( <addEventListener detect> ) {
// W3C DOM Event Model
// Supported by: Firefox, Chrome, Safari, Opera, and (now) IE9
}
else if ( <IE or attachEvent detect> ) {
// Previous IE Event Model code
}
To preventing any parent event handlers from being executed.

addEvent(div, 'mouseover', function(ev) {event =
event || window.event // cross-browser event
if (event.stopPropagation) {
// W3C standard variant
event.stopPropagation()
} else {
// IE variant
event.cancelBubble = true
}
});
JavaScript is an Object Oriented
Programming (OOP) language
 Primitive

Types
 Reference Types
• Boolean true, false

• Number 1, 3.141, -1.602e-19
• String "Joe"
• null null
• undefined undefined
 Only

one number type
 64 bit floating point
 Does not map well to common
understanding of arithmetic
 0.1 + 0.2 = 0.30000000000000004
 Special

number: Not a Number
 Result of undefined or erroneous
operations.
 Toxic: any arithmetic operation with NaN
will have a NaN as a result.
 NaN is not equal anything including NaN
Number(value)
 Convert the value into a number.
 It produces NaN if it has a problem.
parseInt(value,10)
 Convert the value into a number.
 It stops at the first non-digit character.
 The radix (10) should be required
parseInt(“08”) === 0
parseInt(“08”, 10) === 8












abs absolute value
floor integer
log logarithm
max maximum
pow raise to a power
random random number
round nearest integer
sin
sin
sqrt square root
 Unicode

 String

literals can use single or double
quotes.














charAt
concat
indexOf
lastIndexOf
match
replace
search
slice
split
substring
toLowerCase
toUpperCase
A

value that isn’t anything
 Default

value for variables and parameters
 The value of missing members in objects
function isDefined(value) {
return(typeof value != "undefined");
}






Date new Date(1211623944453);
Error new Error("Oops!");
RegExp /^web.*$/i;
Array [ "apple", "banana" ]
Function function(x) {return x*x}
 Date
new Date() ; //Current date
new Date(year, month, day);
Date.parse('2/6/2009');//wrong will depend on culture

 Y2K

Problem

Date.prototype.getRealYear = function()
{
if(this.getFullYear)
return this.getFullYear();
else
return this.getYear() + 1900;
};
unordered collection of properties with
arbitrary values
 object literal
var obj = { name: "Joe", age: 26 };
 setting a property
obj.lastName = "Smith";
 retrieving properties
alert(obj.name + " " + obj.lastName);
Data structure that associates arbitrary
values with arbitrary strings
 property name as an identifier
obj.lastName = "Smith";
 property name as a string
obj["lastName"] = "Smith";
 for( prop in obj ) {
alert( prop + ": " + obj[prop] );
}
Concept of a class does not exist...
... but use a function as a constructor:
 function Dog() {};
class “Dog”
 var lassie = new Dog(); instance “lassie”
 alert(lassie instanceof Dog); // true
Because functions are „first-class objects“
we can attach properties:
 Class Variables
Dog.SPECIES = "Canis lupus";
 Class Methods
Dog.getCount = function() {
return Dog.COUNT;
};
 Instance

Variables
function Dog(name) {
this.name = name;
};
var lassie = new Dog("Lassie");
alert( lassie.name );
 Instance

Methods
function Dog(name) {
this.name = name;
this.bark =
function() { alert("Woof!") };
};
var lassie = new Dog("Lassie");
lassie.bark();
 Global

Scope

• Variables outside of any functions
• Variables inside functions without var

var global1 = 1;
global2 = 2;
function foo() {
global3 = 3;
};
 Function

Scope

• Variables inside functions declared with var
• Function arguments
function foo(local1) {
var local2 = 2;
};
 Block

Scope
... but can be faked:
// before block
(function() {
// inside block
})();
// after block
function Dog(name) {
var _name = name; // private variable
// privileged method
this.getName = function() {
return _name;
};
};
var lassie = new Dog("Lassie");
alert( lassie.getName() );
function Dog(name) {
var _name = name;
// private method
var _fixName = function() {
return _name.toUpperCase();
};
this.getName = function(){
return _fixName();
};
};
 Nested

functions
 Inner function has still access to local
 variables even after the outer function
 has finished
function outer()
{
var count = 1;
function inner() { alert(count++) }
return inner;
}
var myClosure = outer();
myClosure(); // ==> 1
myClosure(); // ==> 2
 function

Pet() {};
Pet

 function

Dog() {};

 Dog.prototype

= new Pet;
Dog
function Pet(name) {
this.name = name;
};
function Dog(name) {
// super(name)
Pet.call( this, name );
this.bark = function() {};
};
Dog.prototype = new Pet;
 //

old: attach to "this“

function Dog(name) {
this.bark =
function(){ alert("Woof!") };
};

 //

new: attach to "prototype"

function Dog(name) {};
Dog.prototype.bark =
function(){ alert("Woof!") };
};
 Property

values on instance:
 local, instance-specific values
 Property values on prototype:
 read-only default values attaching to the
prototype saves memory, especially for
large numbers of instances
 Affects

all new instances
 Affects all existing instances
 Allows modification of existing classes
String.prototype.trim =
function() {
return this.replace(/^s+/, "");
};
alert(" Lassie".trim() );
function Dog() {};
Dog.prototype.bark =
function() { alert("Woof!") };
function Bulldog() {};
Bulldog.prototype = new Dog;
Bulldog.prototype.bark = function() {
// super.bark();
Dog.prototype.bark.call(this);
alert("Grrrh!!") };
function Pet() {
if(this._id == Pet._id) {
throw new Error("No Pets, please!");
}
}
Pet._id = "Pet";
Pet.prototype._id = "Pet";
var fiffy = new Pet; // Error (intended)
But now our code to setup inheritance will
fail:
Dog.prototype = new Pet; // Error :-(
Solution: Do not create an instance of the
actual
superclass just to setup inheritance, use a
dummy:
function Dummy() {};
Dummy.prototype = Pet.prototype;
Dog.prototype = new Dummy;
if (typeof very == "undefined") {
very = {};
}
if (typeof very.cute == "undefined") {
very.cute = {};
}
very.cute.Dog = function() {};
var fiffy = new very.cute.Dog;
// The Last of the Mohicans
var chingachgook = {
fight : function() {
alert("Woah!");
}
};
chingachgook.fight();
function Mohican() {
this.fight = function(){alert("Woah!")}
};
Mohican.getInstance = function() {
if (!this._instance) {
this.instance = new this; }
return this._instance;
};
Mohican.getInstance().fight();


Avoiding Conflicts with Other Libraries ($)

<!-- Putting jQuery into no-conflict mode. -->
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
var $j = jQuery.noConflict();
// $j is now an alias to the jQuery function; creating the new alias is optional.
$j(document).ready(function() {
$j( "div" ).hide();
});
// The $ variable now has the prototype meaning, which is a shortcut for
// document.getElementById(). mainDiv below is a DOM element, not a jQuery object.
window.onload = function() {
var mainDiv = $( "main" );
}
</script>


use multiple window.onload events with external scripts:

window.onload = init;
function addOnloadEvent(fnc){
if ( typeof window.addEventListener != "undefined" )
window.addEventListener( "load", fnc, false );
else if ( typeof window.attachEvent != "undefined" ) {
window.attachEvent( "onload", fnc );
}
else {
if ( window.onload != null ) {var oldOnload = window.onload;
window.onload = function ( e ) {oldOnload( e ); window[fnc]();};
}
else
window.onload = fnc;
}
}
addOnloadEvent(myFunctionName);


Feature-Detect Rather Than Browser-Detect

if (document.getElementById) {
var element = document.getElementById('MyId');
}
else {
alert('Your browser lacks the capabilities required to run this script!');
}


Use Square Bracket Notation
MyObject.property
MyObject."value"+I

(Work)
(not Work)

formref.elements.name[] (not Work)

MyObject["property"] (Work)
MyObject["value"+i] (Work)

formref.elements["name[]"] (Work)


Use onclick In Anchors Instead Of javascript: Pseudo-Protocol
<a href="/" onClick="return validate();">Home</a>
function validate() {
return prompt("Are you sure you want to exit this page?");
}



What Not To Do
<a href="javascript:doSomething()">link</a>
<a href="#" onClick="doSomething()">link</a>
<a href="#" onClick="javascript:doSomething();">link</a>
<a href="#" onClick="javascript:doSomething(); return false;">link</a>


Use The Unary + Operator To TypeConvert To Number

function total() {
var theform = document.forms["myform"];
var total = (+theform.elements["val1"].value) + (+theform.elements["val2"].value);
alert(total); // This will alert 3
}


Don't Use HTML Comments In Script Blocks
<script language="javascript">
<!-// code here
//-->
</script>


Avoid Cluttering The Global Namespace

var MyLib = {}; // global Object cointainer
MyLib.value = 1;
MyLib.increment = function() { MyLib.value++; }
MyLib.show = function() { alert(MyLib.value); }
MyLib.value=6;
MyLib.increment();
MyLib.show(); // alerts 7






Model:
organize the application's data layer.
View:
Templates to render HTML data in controllers and inject them into the DOM.
Composed Views: divide the view into small blocks which can be reused or adapted
to different scenarios.
Controller :
A controller is a list of functions that gets called back when the appropriate event
happens.
 Extend

Methods.
 UI Controls and Library.
 Compatibility.
 Performance.
 Jquery

 The

Dojo Toolkit
 The Yahoo! User Interface Library
 Prototype (and Script.aculo.us)
 MooTools
 ExtJS
provides everything you need to build robust
desktop and mobile web apps.
 JavaScriptMVC

 Knockout
 AngularJS
Framework

UI
Bindings

Composed
Views

Web Presentation
Layer

Plays Nicely
With Others

Backbone.js

✗

✗

✓

✓

SproutCore 1.x

✓

✓

✗

✗

Sammy.js

✗

✗

✓

✓

Spine.js

✗

✗

✓

✓

Cappuccino

✓

✓

✗

✗

Knockout.js

✓

✗

✓

✓

Javascript MVC

✗

✓

✓

✓

Google Web
Toolkit

✗

✓

✗

✗

Google Closure

✗

✓

✓

✗

Ember.js

✓

✓

✓

✓

Angular.js

✓

✗

✓

✓

Batman.js

✓

✗

✓

✓




Define local variables
var doc = document;
elem = doc.getElementById(“objId”);
Combine control conditions and control variable changes when using loops
var x = 9;
do { } while( x-- );


Define arrays for HTML collection objects

function array(items) {
try {
return Array.prototype.concat.call(items);
} catch (ex) {
var i = 0, len = items.length, result = Array(len);
while (i < len) { result[i] = items[i];i++; }
return result;
}
}
var divs = array(
document.getElementsByTagName('div') );
for (var i=0l i < divs.length; i++ ) {
var div = document.createElement("div");
document.appendChild(div);
}


Appending DOM elements all at once faster than adding them individually.


var div = document.getElementsByTagName("div");
var fragment = document.createDocumentFragment();
for ( var e = 0; e < elems.length; e++ ) {
fragment.appendChild( elems[e] );
}

for ( var i = 0; i < div.length; i++ ) {
div[i].appendChild( fragment.cloneNode(true) );
}


Change CSS classes not styles


Optimizing Events
<ul id="menu">
<li id="home">Home</li>
<li id="products">Products</li>
<li id="portfolio">Portfolio</li>
<li id="shop">Shop</li>
</ul>
var menuHandler = function(event) {
event = event || window.event;
var target = event.target || event.srcElement;
if (target.id === 'home') {// go home}
}
document.getElementById('menu').addEventListener('cli
ck',menuHandler);


Avoid memory leaks and circular references in your closures

//Classic case for circular references
function foo(e,d) {
$(e).on("click", function() {
//Do something with d
});
}
//Break the cycle!
function foo(e, d) {
$(e).on("click", cbk(d));
}
function cbk (d) {
}





Avoid using eval
Minimize file size
Caching use external file
Deferred execution


Loading on demand
<script src="lab.js"></script>
<script>
$LAB
.script("jquery.js")
.wait()
.script("jquery.color.js")
.script("jquery.otherplugin.js")
.script("mylib.js")
.wait()
.script("unrelated1.js")
.script("unrelated2.js");
</script>




Minimize file size (use minified files)
Deferred execution
 Frame

 Eval
 Html

Encode:

• escape

• encodeURI
• encodeURIComponent
• html.replace(/</g,"&lt;").replace(/>/g,"&gt;")
 Obfuscate

using tool YUI Compressor. Will
it protect javascript?
TOOLS
 Firebug (FF)
 MS Visual Web Developer (IE)
 DragonFly (Opera)
 Chrome
 Drosera / Web Inspector (Safari)
 Console:

http://code.google.com/p/console-js/
http://patik.com/blog/complete-cross-browserconsole-log/
 Dojo

Shrink Safe
http://shrinksafe.dojotoolkit.org/
 YUI
http://refresh-sf.com/yui/
 Dean Edwards Packer / Compress.js
 Yslow

 Firebug
 Chrome's

development tools
 In

browser (easy) - JSUnit
 Browser Control (comprehensive) –
Selenium
http://www.seleniumhq.org/
 Simulated (fast) – Env.js
http://www.envjs.com/
– Understands JavaScript, hard to
document complex features
http://code.google.com/p/jsdoc-toolkit/
 Natural Docs – Can document anything
 MVCDoc – Can document anything,
understands some JS.
 JSDoc

More Related Content

What's hot

JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript TutorialBui Kiet
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testingVikas Thange
 
Class-based views with Django
Class-based views with DjangoClass-based views with Django
Class-based views with DjangoSimon Willison
 
Activator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetupActivator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetupHenrik Engström
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...Doug Jones
 
Javascript and Jquery Best practices
Javascript and Jquery Best practicesJavascript and Jquery Best practices
Javascript and Jquery Best practicesSultan Khan
 
Why Every Tester Should Learn Ruby
Why Every Tester Should Learn RubyWhy Every Tester Should Learn Ruby
Why Every Tester Should Learn RubyRaimonds Simanovskis
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Librariesjeresig
 
Javascript And J Query
Javascript And J QueryJavascript And J Query
Javascript And J Queryitsarsalan
 
Akka and the Zen of Reactive System Design
Akka and the Zen of Reactive System DesignAkka and the Zen of Reactive System Design
Akka and the Zen of Reactive System DesignLightbend
 
Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practicesManav Gupta
 
Why (I think) CoffeeScript Is Awesome
Why (I think) CoffeeScript Is AwesomeWhy (I think) CoffeeScript Is Awesome
Why (I think) CoffeeScript Is AwesomeJo Cranford
 
jQuery Rescue Adventure
jQuery Rescue AdventurejQuery Rescue Adventure
jQuery Rescue AdventureAllegient
 
Solid Software Design Principles
Solid Software Design PrinciplesSolid Software Design Principles
Solid Software Design PrinciplesJon Kruger
 
How to write easy-to-test JavaScript
How to write easy-to-test JavaScriptHow to write easy-to-test JavaScript
How to write easy-to-test JavaScriptYnon Perek
 
jQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journeyjQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journeyHuiyi Yan
 

What's hot (20)

Rails on Oracle 2011
Rails on Oracle 2011Rails on Oracle 2011
Rails on Oracle 2011
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testing
 
Class-based views with Django
Class-based views with DjangoClass-based views with Django
Class-based views with Django
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
 
Activator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetupActivator and Reactive at Play NYC meetup
Activator and Reactive at Play NYC meetup
 
Intro to JavaScript
Intro to JavaScriptIntro to JavaScript
Intro to JavaScript
 
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
JavaScript: The Good Parts Or: How A C# Developer Learned To Stop Worrying An...
 
Javascript and Jquery Best practices
Javascript and Jquery Best practicesJavascript and Jquery Best practices
Javascript and Jquery Best practices
 
Why Every Tester Should Learn Ruby
Why Every Tester Should Learn RubyWhy Every Tester Should Learn Ruby
Why Every Tester Should Learn Ruby
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 
Javascript And J Query
Javascript And J QueryJavascript And J Query
Javascript And J Query
 
Akka and the Zen of Reactive System Design
Akka and the Zen of Reactive System DesignAkka and the Zen of Reactive System Design
Akka and the Zen of Reactive System Design
 
Javascript best practices
Javascript best practicesJavascript best practices
Javascript best practices
 
Why (I think) CoffeeScript Is Awesome
Why (I think) CoffeeScript Is AwesomeWhy (I think) CoffeeScript Is Awesome
Why (I think) CoffeeScript Is Awesome
 
jQuery Rescue Adventure
jQuery Rescue AdventurejQuery Rescue Adventure
jQuery Rescue Adventure
 
Solid Software Design Principles
Solid Software Design PrinciplesSolid Software Design Principles
Solid Software Design Principles
 
Java script -23jan2015
Java script -23jan2015Java script -23jan2015
Java script -23jan2015
 
How to write easy-to-test JavaScript
How to write easy-to-test JavaScriptHow to write easy-to-test JavaScript
How to write easy-to-test JavaScript
 
jQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journeyjQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journey
 

Similar to Art of Javascript

JavaScript Misunderstood
JavaScript MisunderstoodJavaScript Misunderstood
JavaScript MisunderstoodBhavya Siddappa
 
JavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingJavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingRadoslav Georgiev
 
Painless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldPainless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldChristian Melchior
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to JavascriptAmit Tyagi
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...SPTechCon
 
Javascript Everywhere
Javascript EverywhereJavascript Everywhere
Javascript EverywherePascal Rettig
 
the next web now
the next web nowthe next web now
the next web nowzulin Gu
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingHoat Le
 
Building High Performance Web Applications and Sites
Building High Performance Web Applications and SitesBuilding High Performance Web Applications and Sites
Building High Performance Web Applications and Sitesgoodfriday
 
Ajax and JavaScript Bootcamp
Ajax and JavaScript BootcampAjax and JavaScript Bootcamp
Ajax and JavaScript BootcampAndreCharland
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Domkaven yan
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsJeff Durta
 
JavaScript Essentials in 1 Hour (2018)
JavaScript Essentials in 1 Hour (2018)JavaScript Essentials in 1 Hour (2018)
JavaScript Essentials in 1 Hour (2018)Ahmed Ibrahim
 
jQuery with javascript training by Technnovation Labs
jQuery with javascript training by Technnovation LabsjQuery with javascript training by Technnovation Labs
jQuery with javascript training by Technnovation LabsPrasad Shende
 

Similar to Art of Javascript (20)

JavaScript Misunderstood
JavaScript MisunderstoodJavaScript Misunderstood
JavaScript Misunderstood
 
"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues
 
JavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft TrainingJavaScript Basics - GameCraft Training
JavaScript Basics - GameCraft Training
 
Painless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldPainless Persistence in a Disconnected World
Painless Persistence in a Disconnected World
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
 
Week3
Week3Week3
Week3
 
Javascript Everywhere
Javascript EverywhereJavascript Everywhere
Javascript Everywhere
 
the next web now
the next web nowthe next web now
the next web now
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
Building High Performance Web Applications and Sites
Building High Performance Web Applications and SitesBuilding High Performance Web Applications and Sites
Building High Performance Web Applications and Sites
 
Ajax and JavaScript Bootcamp
Ajax and JavaScript BootcampAjax and JavaScript Bootcamp
Ajax and JavaScript Bootcamp
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
JavaScript Essentials in 1 Hour (2018)
JavaScript Essentials in 1 Hour (2018)JavaScript Essentials in 1 Hour (2018)
JavaScript Essentials in 1 Hour (2018)
 
jQuery with javascript training by Technnovation Labs
jQuery with javascript training by Technnovation LabsjQuery with javascript training by Technnovation Labs
jQuery with javascript training by Technnovation Labs
 

Recently uploaded

APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 

Recently uploaded (20)

APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 

Art of Javascript

  • 1.
  • 2. JavaScript is a lightweight programming language to add interactivity to HTML pages.
  • 3.  Put dynamic text into an HTML page.  React to events  Read and write HTML elements  Validate input data  Detect the visitor's browser  Create cookies
  • 4. New in Html 5:  Access new HTML Elements and Events.  Draw using canvas object  Geolocation: get current location position.  Offline Storage  Post message  Multiple Thread  Socket Programming  Offline web application
  • 5.  Embedded in Html. <script type="text/javascript"><![CDATA[ JavaScript Code ]]></script>  Scripts can be provided locally or remotely. <script language="JavaScript” type="text/javascript“ src="http://somesite/myOwnJavaScript.js"> </script>
  • 6.  Variable scope and declaration.  Popup Boxes: alert("sometext") confirm("sometext") prompt("sometext","defaultvalue")
  • 7.  Conditional statement • if, if.. else, switch  Loop • for loop, while loop  try...catch  Throw  Encapsulate your code into functions
  • 8.
  • 9.  Common Features • DOM Selector • DOM modification • Traversing • Dynamic Styles • Events
  • 10. Compatibility Items:  Elements  Attributes  Browser version  Device/Operating system Detect the visitor's browser var x = "User-agent header sent: " + navigator.userAgent; User-agent header sent: Opera/9.80 (Windows NT 5.1) Presto/2.12.388 Version/12.16
  • 11.
  • 12.
  • 13. var el = document.createElement(“new_el”); element.appendChild(el); document.body.appendChild(el);
  • 14. var fragment = document.createDocumentFragment (); fragment.appendChild(el_1) fragment.appendChild(el_2) fragment.appendChild(el_3) fragment.appendChild(el_4) document.body.appendChild(fragment);
  • 15. var el = document.getElementById(„Id‟);//single element if (document.all || document.getElementById) { ... } val el = document.get ElementsByClassName(„el‟);//select collection of nodes el[0] //get the first element val el = document.get ElementsByTagName(„tagName‟);//select collection of nodes el[0] //get the first element val el = document.get ElementsByTagName(„*‟);//select all tags val el = document.get ElementsByName(„el‟);//select collection of nodes el[0] //get the first element
  • 16. var el = document.querySelector(„#Id‟);//select first element val el = document.querySelector( „.el‟);//select first element val el = document.querySelectorAll( „.el‟);//select collection of nodes
  • 17.  Some old: • getElementById • getElementsByTagNameNot work with object  Some new: • getElementsByClassName  Firefox 3, Safari 3, Opera 9.6, IE9  Opera doesn’t match a second-specified class • querySelectorAll  In Firefox 3.1, Safari 3.1, Opera 10, IE 8  Safari 3.1 had memory out of bounds problems  Safari 3.2 can’t match uppercase characters in quirks mode
  • 19. element.innerHTML = “HTML code”; var attributeValue = element.getAttribute(attributeName); element.setAttribute(attributeName, attributeValue);
  • 21. var el = element.parentNode; var el = element.childNodes; //Elements + White space var el = element.children; //Only Elements var el = element..nextSibling; //next node or null var el = element..previousSibling; //previous node or null var el = element..nextElementSibling; var el = element..previousElementSibling;
  • 22.
  • 23.  onabort - Loading of an image is interrupted  onblur - An element loses focus  onchange - The content of a field changes  onclick - Mouse clicks an object  ondblclick - Mouse double-clicks an object  onerror - An error occurs when loading a document or an image  onfocus - An element gets focus  onkeydown - A keyboard key is pressed
  • 24.  onkeypress - A keyboard key is pressed or held down  onkeyup - A keyboard key is released  onload - A page or an image is finished loading  onmousedown - A mouse button is pressed  onmousemove - The mouse is moved  onmouseout - The mouse is moved off an element  onmouseover - The mouse is moved over an element  onmouseup - A mouse button is released
  • 25.  onreset - The reset button is clicked  onresize A window or frame is resized  onselect - Text is selected  onsubmit - The submit button is clicked  onunload - The user exits the page
  • 26. <img id="myImage" src="http://3.bp.blogspot.com/_ss1KeGx9Bng/THgWaTaHhuI/AAAAAAAAAB0/3PL mvniAdNk/s1600/lolcats_oh-noes_ihasletgo.jpg"> <script> var img = document.getElementById("myImage"), img2=new Image(), originalSrc = img.src; img2.src="https://i.chzbgr.com/maxW500/6073452544/h4B353A81/"; img.onmouseover = function(){ document.getElementById('myImage').src=img2.src; } img.onmouseout = function(){ document.getElementById('myImage').src=originalSrc; } </script>
  • 27. // Internet Explorer element.attachEvent('click', function() { alert(window.event); } ) // Everyone else element.addEventListener('click', function(ev) { alert(ev) }, false );
  • 28.    Bubbling: the event is first captured and handled by the inner most element and then propagated to outer elements. Capturing : event is first captured by the outer most element and propagated to the inner most element. Only event bubbling model is supported by all the major browsers. if ( <addEventListener detect> ) { // W3C DOM Event Model // Supported by: Firefox, Chrome, Safari, Opera, and (now) IE9 } else if ( <IE or attachEvent detect> ) { // Previous IE Event Model code }
  • 29. To preventing any parent event handlers from being executed. addEvent(div, 'mouseover', function(ev) {event = event || window.event // cross-browser event if (event.stopPropagation) { // W3C standard variant event.stopPropagation() } else { // IE variant event.cancelBubble = true } });
  • 30.
  • 31. JavaScript is an Object Oriented Programming (OOP) language
  • 33. • Boolean true, false • Number 1, 3.141, -1.602e-19 • String "Joe" • null null • undefined undefined
  • 34.  Only one number type  64 bit floating point  Does not map well to common understanding of arithmetic  0.1 + 0.2 = 0.30000000000000004
  • 35.  Special number: Not a Number  Result of undefined or erroneous operations.  Toxic: any arithmetic operation with NaN will have a NaN as a result.  NaN is not equal anything including NaN
  • 36. Number(value)  Convert the value into a number.  It produces NaN if it has a problem.
  • 37. parseInt(value,10)  Convert the value into a number.  It stops at the first non-digit character.  The radix (10) should be required parseInt(“08”) === 0 parseInt(“08”, 10) === 8
  • 38.          abs absolute value floor integer log logarithm max maximum pow raise to a power random random number round nearest integer sin sin sqrt square root
  • 39.  Unicode  String literals can use single or double quotes.
  • 42.  Default value for variables and parameters  The value of missing members in objects function isDefined(value) { return(typeof value != "undefined"); }
  • 43.      Date new Date(1211623944453); Error new Error("Oops!"); RegExp /^web.*$/i; Array [ "apple", "banana" ] Function function(x) {return x*x}
  • 44.  Date new Date() ; //Current date new Date(year, month, day); Date.parse('2/6/2009');//wrong will depend on culture  Y2K Problem Date.prototype.getRealYear = function() { if(this.getFullYear) return this.getFullYear(); else return this.getYear() + 1900; };
  • 45. unordered collection of properties with arbitrary values  object literal var obj = { name: "Joe", age: 26 };  setting a property obj.lastName = "Smith";  retrieving properties alert(obj.name + " " + obj.lastName);
  • 46. Data structure that associates arbitrary values with arbitrary strings  property name as an identifier obj.lastName = "Smith";  property name as a string obj["lastName"] = "Smith";  for( prop in obj ) { alert( prop + ": " + obj[prop] ); }
  • 47. Concept of a class does not exist... ... but use a function as a constructor:  function Dog() {}; class “Dog”  var lassie = new Dog(); instance “lassie”  alert(lassie instanceof Dog); // true
  • 48. Because functions are „first-class objects“ we can attach properties:  Class Variables Dog.SPECIES = "Canis lupus";  Class Methods Dog.getCount = function() { return Dog.COUNT; };
  • 49.  Instance Variables function Dog(name) { this.name = name; }; var lassie = new Dog("Lassie"); alert( lassie.name );
  • 50.  Instance Methods function Dog(name) { this.name = name; this.bark = function() { alert("Woof!") }; }; var lassie = new Dog("Lassie"); lassie.bark();
  • 51.  Global Scope • Variables outside of any functions • Variables inside functions without var var global1 = 1; global2 = 2; function foo() { global3 = 3; };
  • 52.  Function Scope • Variables inside functions declared with var • Function arguments function foo(local1) { var local2 = 2; };
  • 53.  Block Scope ... but can be faked: // before block (function() { // inside block })(); // after block
  • 54. function Dog(name) { var _name = name; // private variable // privileged method this.getName = function() { return _name; }; }; var lassie = new Dog("Lassie"); alert( lassie.getName() );
  • 55. function Dog(name) { var _name = name; // private method var _fixName = function() { return _name.toUpperCase(); }; this.getName = function(){ return _fixName(); }; };
  • 56.  Nested functions  Inner function has still access to local  variables even after the outer function  has finished
  • 57. function outer() { var count = 1; function inner() { alert(count++) } return inner; } var myClosure = outer(); myClosure(); // ==> 1 myClosure(); // ==> 2
  • 58.  function Pet() {}; Pet  function Dog() {};  Dog.prototype = new Pet; Dog
  • 59. function Pet(name) { this.name = name; }; function Dog(name) { // super(name) Pet.call( this, name ); this.bark = function() {}; }; Dog.prototype = new Pet;
  • 60.  // old: attach to "this“ function Dog(name) { this.bark = function(){ alert("Woof!") }; };  // new: attach to "prototype" function Dog(name) {}; Dog.prototype.bark = function(){ alert("Woof!") }; };
  • 61.  Property values on instance:  local, instance-specific values  Property values on prototype:  read-only default values attaching to the prototype saves memory, especially for large numbers of instances
  • 62.  Affects all new instances  Affects all existing instances  Allows modification of existing classes String.prototype.trim = function() { return this.replace(/^s+/, ""); }; alert(" Lassie".trim() );
  • 63. function Dog() {}; Dog.prototype.bark = function() { alert("Woof!") }; function Bulldog() {}; Bulldog.prototype = new Dog; Bulldog.prototype.bark = function() { // super.bark(); Dog.prototype.bark.call(this); alert("Grrrh!!") };
  • 64. function Pet() { if(this._id == Pet._id) { throw new Error("No Pets, please!"); } } Pet._id = "Pet"; Pet.prototype._id = "Pet"; var fiffy = new Pet; // Error (intended)
  • 65. But now our code to setup inheritance will fail: Dog.prototype = new Pet; // Error :-( Solution: Do not create an instance of the actual superclass just to setup inheritance, use a dummy: function Dummy() {}; Dummy.prototype = Pet.prototype; Dog.prototype = new Dummy;
  • 66. if (typeof very == "undefined") { very = {}; } if (typeof very.cute == "undefined") { very.cute = {}; } very.cute.Dog = function() {}; var fiffy = new very.cute.Dog;
  • 67. // The Last of the Mohicans var chingachgook = { fight : function() { alert("Woah!"); } }; chingachgook.fight();
  • 68. function Mohican() { this.fight = function(){alert("Woah!")} }; Mohican.getInstance = function() { if (!this._instance) { this.instance = new this; } return this._instance; }; Mohican.getInstance().fight();
  • 69.
  • 70.  Avoiding Conflicts with Other Libraries ($) <!-- Putting jQuery into no-conflict mode. --> <script src="prototype.js"></script> <script src="jquery.js"></script> <script> var $j = jQuery.noConflict(); // $j is now an alias to the jQuery function; creating the new alias is optional. $j(document).ready(function() { $j( "div" ).hide(); }); // The $ variable now has the prototype meaning, which is a shortcut for // document.getElementById(). mainDiv below is a DOM element, not a jQuery object. window.onload = function() { var mainDiv = $( "main" ); } </script>
  • 71.  use multiple window.onload events with external scripts: window.onload = init; function addOnloadEvent(fnc){ if ( typeof window.addEventListener != "undefined" ) window.addEventListener( "load", fnc, false ); else if ( typeof window.attachEvent != "undefined" ) { window.attachEvent( "onload", fnc ); } else { if ( window.onload != null ) {var oldOnload = window.onload; window.onload = function ( e ) {oldOnload( e ); window[fnc]();}; } else window.onload = fnc; } } addOnloadEvent(myFunctionName);
  • 72.  Feature-Detect Rather Than Browser-Detect if (document.getElementById) { var element = document.getElementById('MyId'); } else { alert('Your browser lacks the capabilities required to run this script!'); }  Use Square Bracket Notation MyObject.property MyObject."value"+I (Work) (not Work) formref.elements.name[] (not Work) MyObject["property"] (Work) MyObject["value"+i] (Work) formref.elements["name[]"] (Work)
  • 73.  Use onclick In Anchors Instead Of javascript: Pseudo-Protocol <a href="/" onClick="return validate();">Home</a> function validate() { return prompt("Are you sure you want to exit this page?"); }  What Not To Do <a href="javascript:doSomething()">link</a> <a href="#" onClick="doSomething()">link</a> <a href="#" onClick="javascript:doSomething();">link</a> <a href="#" onClick="javascript:doSomething(); return false;">link</a>
  • 74.  Use The Unary + Operator To TypeConvert To Number function total() { var theform = document.forms["myform"]; var total = (+theform.elements["val1"].value) + (+theform.elements["val2"].value); alert(total); // This will alert 3 }  Don't Use HTML Comments In Script Blocks <script language="javascript"> <!-// code here //--> </script>
  • 75.  Avoid Cluttering The Global Namespace var MyLib = {}; // global Object cointainer MyLib.value = 1; MyLib.increment = function() { MyLib.value++; } MyLib.show = function() { alert(MyLib.value); } MyLib.value=6; MyLib.increment(); MyLib.show(); // alerts 7
  • 76.     Model: organize the application's data layer. View: Templates to render HTML data in controllers and inject them into the DOM. Composed Views: divide the view into small blocks which can be reused or adapted to different scenarios. Controller : A controller is a list of functions that gets called back when the appropriate event happens.
  • 77.
  • 78.
  • 79.  Extend Methods.  UI Controls and Library.  Compatibility.  Performance.
  • 80.  Jquery  The Dojo Toolkit  The Yahoo! User Interface Library  Prototype (and Script.aculo.us)  MooTools  ExtJS provides everything you need to build robust desktop and mobile web apps.
  • 81.
  • 82.
  • 84.
  • 85. Framework UI Bindings Composed Views Web Presentation Layer Plays Nicely With Others Backbone.js ✗ ✗ ✓ ✓ SproutCore 1.x ✓ ✓ ✗ ✗ Sammy.js ✗ ✗ ✓ ✓ Spine.js ✗ ✗ ✓ ✓ Cappuccino ✓ ✓ ✗ ✗ Knockout.js ✓ ✗ ✓ ✓ Javascript MVC ✗ ✓ ✓ ✓ Google Web Toolkit ✗ ✓ ✗ ✗ Google Closure ✗ ✓ ✓ ✗ Ember.js ✓ ✓ ✓ ✓ Angular.js ✓ ✗ ✓ ✓ Batman.js ✓ ✗ ✓ ✓
  • 86.   Define local variables var doc = document; elem = doc.getElementById(“objId”); Combine control conditions and control variable changes when using loops var x = 9; do { } while( x-- );
  • 87.  Define arrays for HTML collection objects function array(items) { try { return Array.prototype.concat.call(items); } catch (ex) { var i = 0, len = items.length, result = Array(len); while (i < len) { result[i] = items[i];i++; } return result; } } var divs = array( document.getElementsByTagName('div') ); for (var i=0l i < divs.length; i++ ) { var div = document.createElement("div"); document.appendChild(div); }
  • 88.  Appending DOM elements all at once faster than adding them individually.  var div = document.getElementsByTagName("div"); var fragment = document.createDocumentFragment(); for ( var e = 0; e < elems.length; e++ ) { fragment.appendChild( elems[e] ); } for ( var i = 0; i < div.length; i++ ) { div[i].appendChild( fragment.cloneNode(true) ); }  Change CSS classes not styles
  • 89.  Optimizing Events <ul id="menu"> <li id="home">Home</li> <li id="products">Products</li> <li id="portfolio">Portfolio</li> <li id="shop">Shop</li> </ul> var menuHandler = function(event) { event = event || window.event; var target = event.target || event.srcElement; if (target.id === 'home') {// go home} } document.getElementById('menu').addEventListener('cli ck',menuHandler);
  • 90.  Avoid memory leaks and circular references in your closures //Classic case for circular references function foo(e,d) { $(e).on("click", function() { //Do something with d }); } //Break the cycle! function foo(e, d) { $(e).on("click", cbk(d)); } function cbk (d) { }     Avoid using eval Minimize file size Caching use external file Deferred execution
  • 91.  Loading on demand <script src="lab.js"></script> <script> $LAB .script("jquery.js") .wait() .script("jquery.color.js") .script("jquery.otherplugin.js") .script("mylib.js") .wait() .script("unrelated1.js") .script("unrelated2.js"); </script>   Minimize file size (use minified files) Deferred execution
  • 92.  Frame  Eval  Html Encode: • escape • encodeURI • encodeURIComponent • html.replace(/</g,"&lt;").replace(/>/g,"&gt;")  Obfuscate using tool YUI Compressor. Will it protect javascript?
  • 93. TOOLS
  • 94.  Firebug (FF)  MS Visual Web Developer (IE)  DragonFly (Opera)  Chrome  Drosera / Web Inspector (Safari)  Console: http://code.google.com/p/console-js/ http://patik.com/blog/complete-cross-browserconsole-log/
  • 95.  Dojo Shrink Safe http://shrinksafe.dojotoolkit.org/  YUI http://refresh-sf.com/yui/  Dean Edwards Packer / Compress.js
  • 96.  Yslow  Firebug  Chrome's development tools
  • 97.  In browser (easy) - JSUnit  Browser Control (comprehensive) – Selenium http://www.seleniumhq.org/  Simulated (fast) – Env.js http://www.envjs.com/
  • 98. – Understands JavaScript, hard to document complex features http://code.google.com/p/jsdoc-toolkit/  Natural Docs – Can document anything  MVCDoc – Can document anything, understands some JS.  JSDoc

Editor's Notes

  1. http://stackoverflow.com/questions/12823264/get-all-elements-in-the-body-tag-using-pure-javascript
  2. Jquery:http://jqueryui.com/demos/The Dojo Toolkit:http://demos.dojotoolkit.org/demos/The Yahoo! User Interface Library:Prototype (and Script.aculo.us):MooToolshttp://mootools.net/demos/Ext JS:http://www.sencha.com/products/extjs/examples/http://docs.sencha.com/extjs/4.2.1/extjs-build/examples/sandbox/sandbox.html
  3. Jquery:http://jqueryui.com/demos/The Dojo Toolkit:http://demos.dojotoolkit.org/demos/The Yahoo! User Interface Library:Prototype (and Script.aculo.us):MooToolshttp://mootools.net/demos/Ext JS:http://www.sencha.com/products/extjs/examples/http://docs.sencha.com/extjs/4.2.1/extjs-build/examples/sandbox/sandbox.html
  4. http://ocanvas.org/demos
  5. Demo:http://learn.knockoutjs.com/#/?tutorial=introhttp://knockoutjs.com/documentation/browser-support.html