SlideShare a Scribd company logo
Javascript Introduction Vu Viet Phuong - Portal Team
Help to approach Javascript easier Objective Prepare to work with eXo javascript framework
Characteristic of Javascript language Subject OOP with Javascript Javascript and DOM Ajax Javascript performance
Characteristic of Javascript language
What is Javascript ? Netscape initially introduced the language under the name LiveScript in an early beta release of Navigator 2.0 in 1995   Some characteristics  :  - Script language - Interpreted - Changing rapidly and Cross-platform support is not consistent JavaScript is the most popular scripting language on the internet
What can We do with it ?   Provide interactive content on your Web pages ( embeded in HTML page using <script> tag )   Much of its power is derived from both the built-in and document objects provided by the browser Control Document Appearance and Content  : document.write(), DOM... Control the Browser  : window.alert(); window.open(); window.close()... Interact with the User  : ability to define &quot;event handlers&quot;
What Javascript can’t do Javascript are confined to browser-related and HTML-related tasks ->  it does not have features that would be required for  standalone  languages Some lack of features :  Graphics capabilities Reading or writing of files Multithreading , except whatever comes implicitly from the web browser's internal use of threads
Quick introduction of basic programming JavaScript is similar to so many other languages:  Arithmetic and logical operators are part of the language Flow-control constructs such as if, while, and switch Example  : - Arithmetic Operators :  + - * / %   The addition operator (+) has a different behavior when operating on strings as opposed to numbers  - Comparison Operators :  > < >= <= != == ===  alert(“10”  ==  10)  //display  true alert(“10”  ===  10) //display  false -  typeof  operator : alert( typeof  “some string”); //display  string http://www.techotopia.com/index.php/JavaScript_Operators
Quick introduction of basic programming Flow control : (if-else, switch) if (expression)  statement;  else statement; Loops :  (while, do-while, for) Loop control  (break and continue) Object-Related Statements: with  Statement :  a shorthand notation when referencing objects w ith(document) {write(“Hello World”);} for…in  : used to loop through an object’s properties for (pros in document) {document.write(pros);} http://en.wikipedia.org/wiki/JavaScript_syntax
Quick introduction of basic programming Script Execution Order :  interpreted line by line as it is found in the page Case Sensitivity  : JavaScript is case-sensitive: keywords, operators.... Statement Delimiters  : Semicolons and Returns Declare Variables :  -  var  keyword - implicit declaration
Data type   Data Type :  - Primitive  data types: number, string, boolean, undefined, null -  Composite  types: objects, arrays, and functions   Dynamic Typing :  T ype is inferred from the variable’s content var test = “10”;  //It's a string test = 10;  //It's a number now
Data type Automatic Type Conversion :  M ost powerful features of JavaScript, as well as the most dangerous for the sloppy programmer window.alert(“10” - 3);  ->  result : 7 Force the conversion  using methods like  toString()  or  parseInt()   DynamicTyping.html
Functions   Function creation syntax  :   function Add(x, y)  { var sum = x + y; return sum; } var test = new Function(“alert('test')”); var test = function() {alert('test')};   How to deal with arguments  :   length  property  arguments [] property FunctionCreation.html
Context, Scope and Closures   Context  :  always be in some form on context (an object within which it's operating)   the way context works is through the  this  variable   Closures  :  I nner functions can refer to the variables in their outer enclosing function    Curring effect   Hide variables from global scope    Scope  :  is  tricky feature.  In Javascript, scope is kept within functions Context.html Scope.html Closures.html http://jibbering.com/faq/notes/closures/
Object-Oriented Programming with JavaScript
Object in Javascript Objects are the fundamental units of JavaScript EVERYTHING except primative type in JavaScript is object There are three object categories in JavaScript:   Native Objects Host Objects User-Defined Objects
Object creation 1. Using  new Object() employee = new Object() employee.name = &quot;Tim&quot;; employee.say = function() { alert('hello'); } 2. Using Literal Notation employee = { name : &quot;Tim&quot;, say : function() { alert('hello') } }; NOT reusable- we cannot easily initialize different versions of the created object
Object creation 3. Object Constructor : - Regular JavaScript function - The difference is that, it is called via 'new' operator, without this, it just likes other javascript method // it to the current context  function User( name ) {  this.name = name;  }  // Create a new instance of that function var me = new User( &quot;My Name&quot; ); 3. Object Constructor : - Regular JavaScript function - The difference is that, it is called via 'new' operator, without this, it just likes other javascript method
Object creation Now, since User() is just a function what happens when we treat it as such?   User( &quot;Test&quot; );  // Since its 'this' context wasn't set  // it defaults to the global 'window'  alert( window.name == &quot;Test&quot; );  //  display true ObjectCreation.html
Prototype Prototyping is the key to understanding the inheritance concept “ prototype”  is a property of every function. Since constructor is also function, it's a property of constructor too  function User(){};  var test = new User(); User.prototype.say = function() {alert('hello')}; test.say();  //display hello ObjectCreation_Prototype.html
Inheritance Inheritance is the ability to have properties from “Super Class” Set  prototype  property of constructor to an “super class” object -> “ sub class” object will have access to “super class” properties function SuperClass() { this.superHello = function() {alert(“super hello”)} } function SubClass(){} SubClass.prototype = new SuperClass(); Inheritance.html
Encapsulation Objects interact with each other via call method, and don't know what is happening inside Private  : only accessible to other private methods or privileged methods function Bean() { var name = &quot;test&quot;; //Getter this.getName = function() {return name}; //Setter this.setName = function(newName) {name = newName}; } Encapsulation.html
Polymorphism Polymorphism  : is a programming language feature that allows values of different data types to be handled using a uniform interface In  java,  we can achieve this by implementing an interface In weakly typed languages like JavaScript,  types are implicitly  polymorphic http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming
Namespace help us to avoid name conflic Javascript, natively doesn't provide namespace feature Namespacing Workaround for this : var   =   {   DOMUtil   :   {   },   … . }; //After define DOMUtil, we use it in namespace like that eXo.core.DOMUtil   =   new   DOMUtil()   ; Namespace.html
Javascript and DOM
DOM : Document Object Model  Dom is programming interface for HTML and XML documents It provides a structured representation of the document Javascript and DOM <html> <head>...</head> <body> <h1>Hello World!</h1> </body> </html> // Does not work! -> text is also consisdered a node  document.documentElement.firstChild.nextSibling.firstChild DOMExample.html
There are a number of possible values  The three that you’ll encounter the most are the following:  Element  (nodeType = 1),  Text  (3),  Document  (9) Node types http://www.javascriptkit.com/domref/nodetype.shtml
API document and window objects are the objects whose interfaces  you generally use most often in DOM programming   window object represents the window itself window.alert(); window.open(); window.scrollTo()   document property of window points to the DOM document  loaded in that window http://www.w3schools.com/jsref/obj_window.asp
document The document provides methods for creating and manipulating all of the document's child nodes, or elements Creating and Retrieving elements:   document.getElementById(id), document.createElement(name) Get and Set Attributes: document.getAttribute(name), document.setAttribute(name,val) https://developer.mozilla.org/en/Gecko_DOM_Reference Document.html
CSS There are two problems that you encounter when working with CSS properties on DOM elements Second, can't get pre-set style. We must get the computed style First, JavaScript requires that you specify the  unit  of size for setting any dimensional property document.getElementById(“table”).style.width = “200 px ”; StyleTest.html
DOM Event Events are actions on DOM that can be detected by JavaScript Every element on a web page has certain events which can trigger JavaScript functions Examples of events: -  A mouse click -  A web page or an image loading -  Mousing over a hot spot on the web page
Event Phases Javascript events are executed in 2 phases  Capturing : event moving down the DOM tree to the element that instantiated event Bubbling phase traverses up DOM tree to the root element Bubbing.html Capturing.html
Event object Contains contextual information about the current event IE’s implementation is  different  from the W3C’s specification function eventHandler(evt) { var e = window.event || evt; ... } Default behaviour :  Browser has some default actions that will always occur click <a> element -> redirect to other page press key on textbox -> display chars on textbox
Control event Overriding the Browser’s Default Action : if ( e && e.preventDefault ) e. preventDefault (); else  //IE window.event. returnValue  = false; Stop bubbling :  if ( e && e.stopPropagation ) e. stopPropagation (); else window.event. cancelBubble  = true; OverrideDefaultAction.html StopBubbling.html
Event handler Traditional Binding document.body.onclick(handler); W3C method of binding event handlers document.body.addEventListener('click', handler, false); IE’s method document.body.attachEvent(' onclick ', myKeyPressHandler); https://developer.mozilla.org/en/DOM/event
Ajax
Definition Ajax (Asynchronous JavaScript and XML) AJAX uses a combination of :  DOM   XMLHttpRequest   XML  is sometimes used as the format for transferring data between the server and client, although any format will work
How it work Request process can be handled  asynchronously Then a  SMALL  portion of desired results can be loaded upon completion
Make request Create XMLHttpRequest Object - Internet Exployer 5, 6:     new ActiveXObject(&quot;Microsoft.XMLHTTP&quot;); - IE7+, Firefox, Chrome, Opera, Safari  :   new XMLHttpRequest(); Establishing a Connection : GET  or  POST  request // Open the socket  ajx.open(&quot;GET&quot;, &quot;/some/url&quot;, true);  // Establish the connection to the server  ajx.send();
Send data Serializing Data:  function User() {  name: &quot;John&quot;,  last: &quot;Resig&quot; }  // Serialized form  serObj =  name=John&last=Resig Request method : GET   ajx.open(&quot;GET&quot;, &quot;/some/url?&quot;  +  serObj , true);  ajx.send(); Request method : POST   ajx.open(&quot;POST&quot;, &quot;/some/url&quot;, true); ajx. setRequestHeader ( &quot;Content-Type&quot;,  &quot; application/x-www-form-urlencoded &quot;); ajx.send(  serObj  );
Handle response readyState property :  request lifecycle 0 : uninitialized 1 : connection establised 2 : request received 3 : processing 4 : finished   onreadystatechange  property     Successful  response codes: 200 <= ajx.status < 300 Not modified response  : 304 (Safari : undefined) Every other codes will be considered error
Update UI Reading the Resulting Data responseXML :  This property will contain a reference to a precomputed DOM document responseText :  This property contains a reference to the raw text string of data returned by the server ajx.onreadystatechange = function(){  if (  ajx.readyState == 4 ) {  if ( ajx.status >= 200 && ajx.status < 300 ) { var scores = document.getElementById(&quot;testDiv&quot;);  scores.innerText = ajx. responseText ; } }  }; Example http://www.learn-ajax-tutorial.com/
Javascript Performance
Some tips DOM access :  Interaction with the DOM is usually slower than normal JavaScript code   for-in loops :  most JS environments have slow implementation eval and Function constructor :  avoid using because overhead is involved in script evaluation //expensive operations var func = new Function(“alert('test')”); Pass  functions , not strings, to  setTimeout () and  setInterval ()  http://wiki.forum.nokia.com/index.php/JavaScript_Performance_Best_Practices
Ad

More Related Content

What's hot (20)

JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
Mats Bryntse
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
Aaron Gustafson
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
Bala Narayanan
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
Walid Ashraf
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
Amit Tyagi
 
JavaScript 101 - Class 1
JavaScript 101 - Class 1JavaScript 101 - Class 1
JavaScript 101 - Class 1
Robert Pearce
 
Parte II Objective C
Parte II   Objective CParte II   Objective C
Parte II Objective C
Paolo Quadrani
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UX
JWORKS powered by Ordina
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
Sehwan Noh
 
A Re-Introduction to JavaScript
A Re-Introduction to JavaScriptA Re-Introduction to JavaScript
A Re-Introduction to JavaScript
Simon Willison
 
Javascript 101
Javascript 101Javascript 101
Javascript 101
Shlomi Komemi
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScript
Todd Anglin
 
Javascript session 01 - Introduction to Javascript
Javascript session 01 - Introduction to JavascriptJavascript session 01 - Introduction to Javascript
Javascript session 01 - Introduction to Javascript
Livingston Samuel
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testing
Vikas Thange
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best Practices
Dragos Ionita
 
Javascript
JavascriptJavascript
Javascript
Manav Prasad
 
Java script
Java scriptJava script
Java script
Adrian Caetano
 
Anonymous functions in JavaScript
Anonymous functions in JavaScriptAnonymous functions in JavaScript
Anonymous functions in JavaScript
Mohammed Sazid Al Rashid
 
Javascript
JavascriptJavascript
Javascript
Gita Kriz
 
Java Script Best Practices
Java Script Best PracticesJava Script Best Practices
Java Script Best Practices
Enrique Juan de Dios
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
Aaron Gustafson
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
Walid Ashraf
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
Amit Tyagi
 
JavaScript 101 - Class 1
JavaScript 101 - Class 1JavaScript 101 - Class 1
JavaScript 101 - Class 1
Robert Pearce
 
JavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UXJavaScript Basics and Best Practices - CC FE & UX
JavaScript Basics and Best Practices - CC FE & UX
JWORKS powered by Ordina
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
Sehwan Noh
 
A Re-Introduction to JavaScript
A Re-Introduction to JavaScriptA Re-Introduction to JavaScript
A Re-Introduction to JavaScript
Simon Willison
 
5 Tips for Better JavaScript
5 Tips for Better JavaScript5 Tips for Better JavaScript
5 Tips for Better JavaScript
Todd Anglin
 
Javascript session 01 - Introduction to Javascript
Javascript session 01 - Introduction to JavascriptJavascript session 01 - Introduction to Javascript
Javascript session 01 - Introduction to Javascript
Livingston Samuel
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testing
Vikas Thange
 
Powerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best PracticesPowerful JavaScript Tips and Best Practices
Powerful JavaScript Tips and Best Practices
Dragos Ionita
 

Viewers also liked (20)

Verteilte versionsverwaltung mit Team Foundation Server 2012
Verteilte versionsverwaltung mit Team Foundation Server 2012Verteilte versionsverwaltung mit Team Foundation Server 2012
Verteilte versionsverwaltung mit Team Foundation Server 2012
Daniel Marbach
 
jQuery Fundamentals
jQuery FundamentalsjQuery Fundamentals
jQuery Fundamentals
Doncho Minkov
 
Web vr creative_vr
Web vr creative_vrWeb vr creative_vr
Web vr creative_vr
Oscar Marin Miro
 
Estudo 01
Estudo 01Estudo 01
Estudo 01
Renato Florentino
 
Firefox Extension Development
Firefox Extension DevelopmentFirefox Extension Development
Firefox Extension Development
phamvanvung
 
Quick dive into WebVR
Quick dive into WebVRQuick dive into WebVR
Quick dive into WebVR
Janne Aukia
 
WebVR with Three.js!
WebVR with Three.js!WebVR with Three.js!
WebVR with Three.js!
誠人 堀口
 
JavaScript Web Workers
JavaScript Web WorkersJavaScript Web Workers
JavaScript Web Workers
Tobias Pfeiffer
 
WebRTC - On Standards, Identity and Telco Strategy
WebRTC - On Standards, Identity and Telco StrategyWebRTC - On Standards, Identity and Telco Strategy
WebRTC - On Standards, Identity and Telco Strategy
Jose de Castro
 
WebVR - JAX 2016
WebVR -  JAX 2016WebVR -  JAX 2016
WebVR - JAX 2016
Carsten Sandtner
 
Javascript the New Parts
Javascript the New PartsJavascript the New Parts
Javascript the New Parts
Federico Galassi
 
Introduction to The VR Web
Introduction to The VR WebIntroduction to The VR Web
Introduction to The VR Web
Liv Erickson
 
20160713 webvr
20160713 webvr20160713 webvr
20160713 webvr
Noritada Shimizu
 
WebRTC: A front-end perspective
WebRTC: A front-end perspectiveWebRTC: A front-end perspective
WebRTC: A front-end perspective
shwetank
 
JavaScript and Web Standards Sitting in a Tree
JavaScript and Web Standards Sitting in a TreeJavaScript and Web Standards Sitting in a Tree
JavaScript and Web Standards Sitting in a Tree
Jenn Lukas
 
Web Front End - (HTML5, CSS3, JavaScript) ++
Web Front End - (HTML5, CSS3, JavaScript) ++Web Front End - (HTML5, CSS3, JavaScript) ++
Web Front End - (HTML5, CSS3, JavaScript) ++
ubshreenath
 
Photo and photo
Photo and photoPhoto and photo
Photo and photo
arreeluckdang
 
WebRTC Reborn - Cloud Expo / WebRTC Summit
WebRTC Reborn - Cloud Expo / WebRTC SummitWebRTC Reborn - Cloud Expo / WebRTC Summit
WebRTC Reborn - Cloud Expo / WebRTC Summit
Dan Jenkins
 
Introduction to WebGL and WebVR
Introduction to WebGL and WebVRIntroduction to WebGL and WebVR
Introduction to WebGL and WebVR
Daosheng Mu
 
The next frontier: WebGL and WebVR
The next frontier: WebGL and WebVRThe next frontier: WebGL and WebVR
The next frontier: WebGL and WebVR
Codemotion
 
Verteilte versionsverwaltung mit Team Foundation Server 2012
Verteilte versionsverwaltung mit Team Foundation Server 2012Verteilte versionsverwaltung mit Team Foundation Server 2012
Verteilte versionsverwaltung mit Team Foundation Server 2012
Daniel Marbach
 
Firefox Extension Development
Firefox Extension DevelopmentFirefox Extension Development
Firefox Extension Development
phamvanvung
 
Quick dive into WebVR
Quick dive into WebVRQuick dive into WebVR
Quick dive into WebVR
Janne Aukia
 
WebVR with Three.js!
WebVR with Three.js!WebVR with Three.js!
WebVR with Three.js!
誠人 堀口
 
WebRTC - On Standards, Identity and Telco Strategy
WebRTC - On Standards, Identity and Telco StrategyWebRTC - On Standards, Identity and Telco Strategy
WebRTC - On Standards, Identity and Telco Strategy
Jose de Castro
 
Introduction to The VR Web
Introduction to The VR WebIntroduction to The VR Web
Introduction to The VR Web
Liv Erickson
 
WebRTC: A front-end perspective
WebRTC: A front-end perspectiveWebRTC: A front-end perspective
WebRTC: A front-end perspective
shwetank
 
JavaScript and Web Standards Sitting in a Tree
JavaScript and Web Standards Sitting in a TreeJavaScript and Web Standards Sitting in a Tree
JavaScript and Web Standards Sitting in a Tree
Jenn Lukas
 
Web Front End - (HTML5, CSS3, JavaScript) ++
Web Front End - (HTML5, CSS3, JavaScript) ++Web Front End - (HTML5, CSS3, JavaScript) ++
Web Front End - (HTML5, CSS3, JavaScript) ++
ubshreenath
 
WebRTC Reborn - Cloud Expo / WebRTC Summit
WebRTC Reborn - Cloud Expo / WebRTC SummitWebRTC Reborn - Cloud Expo / WebRTC Summit
WebRTC Reborn - Cloud Expo / WebRTC Summit
Dan Jenkins
 
Introduction to WebGL and WebVR
Introduction to WebGL and WebVRIntroduction to WebGL and WebVR
Introduction to WebGL and WebVR
Daosheng Mu
 
The next frontier: WebGL and WebVR
The next frontier: WebGL and WebVRThe next frontier: WebGL and WebVR
The next frontier: WebGL and WebVR
Codemotion
 
Ad

Similar to eXo SEA - JavaScript Introduction Training (20)

JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom Manipulation
Mohammed Arif
 
Scripting The Dom
Scripting The DomScripting The Dom
Scripting The Dom
Ara Pehlivanian
 
Advisor Jumpstart: JavaScript
Advisor Jumpstart: JavaScriptAdvisor Jumpstart: JavaScript
Advisor Jumpstart: JavaScript
dominion
 
J Query
J QueryJ Query
J Query
ravinxg
 
JS basics
JS basicsJS basics
JS basics
Mohd Saeed
 
"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues
Núcleo de Electrónica e Informática da Universidade do Algarve
 
My 70-480 HTML5 certification learning
My 70-480 HTML5 certification learningMy 70-480 HTML5 certification learning
My 70-480 HTML5 certification learning
Syed Irtaza Ali
 
Reversing JavaScript
Reversing JavaScriptReversing JavaScript
Reversing JavaScript
Roberto Suggi Liverani
 
JavaScript Misunderstood
JavaScript MisunderstoodJavaScript Misunderstood
JavaScript Misunderstood
Bhavya Siddappa
 
Javascript Templating
Javascript TemplatingJavascript Templating
Javascript Templating
bcruhl
 
Modern JavaScript Programming
Modern JavaScript Programming Modern JavaScript Programming
Modern JavaScript Programming
Wildan Maulana
 
IWT presentation121232112122222225556+556.pptx
IWT presentation121232112122222225556+556.pptxIWT presentation121232112122222225556+556.pptx
IWT presentation121232112122222225556+556.pptx
dgfs55437
 
Eugene Andruszczenko: jQuery
Eugene Andruszczenko: jQueryEugene Andruszczenko: jQuery
Eugene Andruszczenko: jQuery
Refresh Events
 
jQuery Presentation - Refresh Events
jQuery Presentation - Refresh EventsjQuery Presentation - Refresh Events
jQuery Presentation - Refresh Events
Eugene Andruszczenko
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
kaven yan
 
Wt unit 5
Wt unit 5Wt unit 5
Wt unit 5
team11vgnt
 
JavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM ManipulationJavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM Manipulation
borkweb
 
Javazone 2010-lift-framework-public
Javazone 2010-lift-framework-publicJavazone 2010-lift-framework-public
Javazone 2010-lift-framework-public
Timothy Perrett
 
ActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group PresentationActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group Presentation
ipolevoy
 
Sencha / ExtJS : Object Oriented JavaScript
Sencha / ExtJS : Object Oriented JavaScriptSencha / ExtJS : Object Oriented JavaScript
Sencha / ExtJS : Object Oriented JavaScript
Rohan Chandane
 
JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom Manipulation
Mohammed Arif
 
Advisor Jumpstart: JavaScript
Advisor Jumpstart: JavaScriptAdvisor Jumpstart: JavaScript
Advisor Jumpstart: JavaScript
dominion
 
My 70-480 HTML5 certification learning
My 70-480 HTML5 certification learningMy 70-480 HTML5 certification learning
My 70-480 HTML5 certification learning
Syed Irtaza Ali
 
JavaScript Misunderstood
JavaScript MisunderstoodJavaScript Misunderstood
JavaScript Misunderstood
Bhavya Siddappa
 
Javascript Templating
Javascript TemplatingJavascript Templating
Javascript Templating
bcruhl
 
Modern JavaScript Programming
Modern JavaScript Programming Modern JavaScript Programming
Modern JavaScript Programming
Wildan Maulana
 
IWT presentation121232112122222225556+556.pptx
IWT presentation121232112122222225556+556.pptxIWT presentation121232112122222225556+556.pptx
IWT presentation121232112122222225556+556.pptx
dgfs55437
 
Eugene Andruszczenko: jQuery
Eugene Andruszczenko: jQueryEugene Andruszczenko: jQuery
Eugene Andruszczenko: jQuery
Refresh Events
 
jQuery Presentation - Refresh Events
jQuery Presentation - Refresh EventsjQuery Presentation - Refresh Events
jQuery Presentation - Refresh Events
Eugene Andruszczenko
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
kaven yan
 
JavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM ManipulationJavaScript: Ajax & DOM Manipulation
JavaScript: Ajax & DOM Manipulation
borkweb
 
Javazone 2010-lift-framework-public
Javazone 2010-lift-framework-publicJavazone 2010-lift-framework-public
Javazone 2010-lift-framework-public
Timothy Perrett
 
ActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group PresentationActiveWeb: Chicago Java User Group Presentation
ActiveWeb: Chicago Java User Group Presentation
ipolevoy
 
Sencha / ExtJS : Object Oriented JavaScript
Sencha / ExtJS : Object Oriented JavaScriptSencha / ExtJS : Object Oriented JavaScript
Sencha / ExtJS : Object Oriented JavaScript
Rohan Chandane
 
Ad

More from Hoat Le (14)

Scrum in Action
Scrum in ActionScrum in Action
Scrum in Action
Hoat Le
 
Advanced JavaScript Techniques
Advanced JavaScript TechniquesAdvanced JavaScript Techniques
Advanced JavaScript Techniques
Hoat Le
 
eXo EC - LaTeX
eXo EC - LaTeXeXo EC - LaTeX
eXo EC - LaTeX
Hoat Le
 
eXo EC - Groovy Programming Language
eXo EC - Groovy Programming LanguageeXo EC - Groovy Programming Language
eXo EC - Groovy Programming Language
Hoat Le
 
Barcamphanoi Opensocial Application Development
Barcamphanoi Opensocial Application DevelopmentBarcamphanoi Opensocial Application Development
Barcamphanoi Opensocial Application Development
Hoat Le
 
San xuat sach hon
San xuat sach honSan xuat sach hon
San xuat sach hon
Hoat Le
 
E-goverment
E-govermentE-goverment
E-goverment
Hoat Le
 
Dien Giai Moi Truong
Dien Giai Moi TruongDien Giai Moi Truong
Dien Giai Moi Truong
Hoat Le
 
E-Commerce
E-CommerceE-Commerce
E-Commerce
Hoat Le
 
unit 15, nuclear energy
unit 15, nuclear energyunit 15, nuclear energy
unit 15, nuclear energy
Hoat Le
 
Linux Os
Linux OsLinux Os
Linux Os
Hoat Le
 
Unit 1 Types Of Computers
Unit 1 Types Of ComputersUnit 1 Types Of Computers
Unit 1 Types Of Computers
Hoat Le
 
Unit 0 Introduction To Computer
Unit 0 Introduction To ComputerUnit 0 Introduction To Computer
Unit 0 Introduction To Computer
Hoat Le
 
Scrum in Action
Scrum in ActionScrum in Action
Scrum in Action
Hoat Le
 
Advanced JavaScript Techniques
Advanced JavaScript TechniquesAdvanced JavaScript Techniques
Advanced JavaScript Techniques
Hoat Le
 
eXo EC - LaTeX
eXo EC - LaTeXeXo EC - LaTeX
eXo EC - LaTeX
Hoat Le
 
eXo EC - Groovy Programming Language
eXo EC - Groovy Programming LanguageeXo EC - Groovy Programming Language
eXo EC - Groovy Programming Language
Hoat Le
 
Barcamphanoi Opensocial Application Development
Barcamphanoi Opensocial Application DevelopmentBarcamphanoi Opensocial Application Development
Barcamphanoi Opensocial Application Development
Hoat Le
 
San xuat sach hon
San xuat sach honSan xuat sach hon
San xuat sach hon
Hoat Le
 
E-goverment
E-govermentE-goverment
E-goverment
Hoat Le
 
Dien Giai Moi Truong
Dien Giai Moi TruongDien Giai Moi Truong
Dien Giai Moi Truong
Hoat Le
 
E-Commerce
E-CommerceE-Commerce
E-Commerce
Hoat Le
 
unit 15, nuclear energy
unit 15, nuclear energyunit 15, nuclear energy
unit 15, nuclear energy
Hoat Le
 
Linux Os
Linux OsLinux Os
Linux Os
Hoat Le
 
Unit 1 Types Of Computers
Unit 1 Types Of ComputersUnit 1 Types Of Computers
Unit 1 Types Of Computers
Hoat Le
 
Unit 0 Introduction To Computer
Unit 0 Introduction To ComputerUnit 0 Introduction To Computer
Unit 0 Introduction To Computer
Hoat Le
 

Recently uploaded (20)

Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptxIncreasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Increasing Retail Store Efficiency How can Planograms Save Time and Money.pptx
Anoop Ashok
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 

eXo SEA - JavaScript Introduction Training

  • 1. Javascript Introduction Vu Viet Phuong - Portal Team
  • 2. Help to approach Javascript easier Objective Prepare to work with eXo javascript framework
  • 3. Characteristic of Javascript language Subject OOP with Javascript Javascript and DOM Ajax Javascript performance
  • 5. What is Javascript ? Netscape initially introduced the language under the name LiveScript in an early beta release of Navigator 2.0 in 1995 Some characteristics : - Script language - Interpreted - Changing rapidly and Cross-platform support is not consistent JavaScript is the most popular scripting language on the internet
  • 6. What can We do with it ? Provide interactive content on your Web pages ( embeded in HTML page using <script> tag ) Much of its power is derived from both the built-in and document objects provided by the browser Control Document Appearance and Content : document.write(), DOM... Control the Browser : window.alert(); window.open(); window.close()... Interact with the User : ability to define &quot;event handlers&quot;
  • 7. What Javascript can’t do Javascript are confined to browser-related and HTML-related tasks -> it does not have features that would be required for standalone languages Some lack of features : Graphics capabilities Reading or writing of files Multithreading , except whatever comes implicitly from the web browser's internal use of threads
  • 8. Quick introduction of basic programming JavaScript is similar to so many other languages: Arithmetic and logical operators are part of the language Flow-control constructs such as if, while, and switch Example : - Arithmetic Operators : + - * / % The addition operator (+) has a different behavior when operating on strings as opposed to numbers - Comparison Operators : > < >= <= != == === alert(“10” == 10) //display true alert(“10” === 10) //display false - typeof operator : alert( typeof “some string”); //display string http://www.techotopia.com/index.php/JavaScript_Operators
  • 9. Quick introduction of basic programming Flow control : (if-else, switch) if (expression) statement; else statement; Loops : (while, do-while, for) Loop control (break and continue) Object-Related Statements: with Statement : a shorthand notation when referencing objects w ith(document) {write(“Hello World”);} for…in : used to loop through an object’s properties for (pros in document) {document.write(pros);} http://en.wikipedia.org/wiki/JavaScript_syntax
  • 10. Quick introduction of basic programming Script Execution Order : interpreted line by line as it is found in the page Case Sensitivity : JavaScript is case-sensitive: keywords, operators.... Statement Delimiters : Semicolons and Returns Declare Variables : - var keyword - implicit declaration
  • 11. Data type Data Type : - Primitive data types: number, string, boolean, undefined, null - Composite types: objects, arrays, and functions Dynamic Typing : T ype is inferred from the variable’s content var test = “10”; //It's a string test = 10; //It's a number now
  • 12. Data type Automatic Type Conversion : M ost powerful features of JavaScript, as well as the most dangerous for the sloppy programmer window.alert(“10” - 3); -> result : 7 Force the conversion using methods like toString() or parseInt() DynamicTyping.html
  • 13. Functions Function creation syntax : function Add(x, y) { var sum = x + y; return sum; } var test = new Function(“alert('test')”); var test = function() {alert('test')}; How to deal with arguments : length property arguments [] property FunctionCreation.html
  • 14. Context, Scope and Closures Context : always be in some form on context (an object within which it's operating) the way context works is through the this variable Closures : I nner functions can refer to the variables in their outer enclosing function Curring effect Hide variables from global scope Scope : is tricky feature. In Javascript, scope is kept within functions Context.html Scope.html Closures.html http://jibbering.com/faq/notes/closures/
  • 16. Object in Javascript Objects are the fundamental units of JavaScript EVERYTHING except primative type in JavaScript is object There are three object categories in JavaScript: Native Objects Host Objects User-Defined Objects
  • 17. Object creation 1. Using new Object() employee = new Object() employee.name = &quot;Tim&quot;; employee.say = function() { alert('hello'); } 2. Using Literal Notation employee = { name : &quot;Tim&quot;, say : function() { alert('hello') } }; NOT reusable- we cannot easily initialize different versions of the created object
  • 18. Object creation 3. Object Constructor : - Regular JavaScript function - The difference is that, it is called via 'new' operator, without this, it just likes other javascript method // it to the current context function User( name ) { this.name = name; } // Create a new instance of that function var me = new User( &quot;My Name&quot; ); 3. Object Constructor : - Regular JavaScript function - The difference is that, it is called via 'new' operator, without this, it just likes other javascript method
  • 19. Object creation Now, since User() is just a function what happens when we treat it as such? User( &quot;Test&quot; ); // Since its 'this' context wasn't set // it defaults to the global 'window' alert( window.name == &quot;Test&quot; ); // display true ObjectCreation.html
  • 20. Prototype Prototyping is the key to understanding the inheritance concept “ prototype” is a property of every function. Since constructor is also function, it's a property of constructor too function User(){}; var test = new User(); User.prototype.say = function() {alert('hello')}; test.say(); //display hello ObjectCreation_Prototype.html
  • 21. Inheritance Inheritance is the ability to have properties from “Super Class” Set prototype property of constructor to an “super class” object -> “ sub class” object will have access to “super class” properties function SuperClass() { this.superHello = function() {alert(“super hello”)} } function SubClass(){} SubClass.prototype = new SuperClass(); Inheritance.html
  • 22. Encapsulation Objects interact with each other via call method, and don't know what is happening inside Private : only accessible to other private methods or privileged methods function Bean() { var name = &quot;test&quot;; //Getter this.getName = function() {return name}; //Setter this.setName = function(newName) {name = newName}; } Encapsulation.html
  • 23. Polymorphism Polymorphism : is a programming language feature that allows values of different data types to be handled using a uniform interface In java, we can achieve this by implementing an interface In weakly typed languages like JavaScript, types are implicitly polymorphic http://en.wikipedia.org/wiki/Polymorphism_in_object-oriented_programming
  • 24. Namespace help us to avoid name conflic Javascript, natively doesn't provide namespace feature Namespacing Workaround for this : var = { DOMUtil : { }, … . }; //After define DOMUtil, we use it in namespace like that eXo.core.DOMUtil = new DOMUtil() ; Namespace.html
  • 26. DOM : Document Object Model Dom is programming interface for HTML and XML documents It provides a structured representation of the document Javascript and DOM <html> <head>...</head> <body> <h1>Hello World!</h1> </body> </html> // Does not work! -> text is also consisdered a node document.documentElement.firstChild.nextSibling.firstChild DOMExample.html
  • 27. There are a number of possible values The three that you’ll encounter the most are the following: Element (nodeType = 1), Text (3), Document (9) Node types http://www.javascriptkit.com/domref/nodetype.shtml
  • 28. API document and window objects are the objects whose interfaces you generally use most often in DOM programming window object represents the window itself window.alert(); window.open(); window.scrollTo() document property of window points to the DOM document loaded in that window http://www.w3schools.com/jsref/obj_window.asp
  • 29. document The document provides methods for creating and manipulating all of the document's child nodes, or elements Creating and Retrieving elements: document.getElementById(id), document.createElement(name) Get and Set Attributes: document.getAttribute(name), document.setAttribute(name,val) https://developer.mozilla.org/en/Gecko_DOM_Reference Document.html
  • 30. CSS There are two problems that you encounter when working with CSS properties on DOM elements Second, can't get pre-set style. We must get the computed style First, JavaScript requires that you specify the unit of size for setting any dimensional property document.getElementById(“table”).style.width = “200 px ”; StyleTest.html
  • 31. DOM Event Events are actions on DOM that can be detected by JavaScript Every element on a web page has certain events which can trigger JavaScript functions Examples of events: - A mouse click - A web page or an image loading - Mousing over a hot spot on the web page
  • 32. Event Phases Javascript events are executed in 2 phases Capturing : event moving down the DOM tree to the element that instantiated event Bubbling phase traverses up DOM tree to the root element Bubbing.html Capturing.html
  • 33. Event object Contains contextual information about the current event IE’s implementation is different from the W3C’s specification function eventHandler(evt) { var e = window.event || evt; ... } Default behaviour : Browser has some default actions that will always occur click <a> element -> redirect to other page press key on textbox -> display chars on textbox
  • 34. Control event Overriding the Browser’s Default Action : if ( e && e.preventDefault ) e. preventDefault (); else //IE window.event. returnValue = false; Stop bubbling : if ( e && e.stopPropagation ) e. stopPropagation (); else window.event. cancelBubble = true; OverrideDefaultAction.html StopBubbling.html
  • 35. Event handler Traditional Binding document.body.onclick(handler); W3C method of binding event handlers document.body.addEventListener('click', handler, false); IE’s method document.body.attachEvent(' onclick ', myKeyPressHandler); https://developer.mozilla.org/en/DOM/event
  • 36. Ajax
  • 37. Definition Ajax (Asynchronous JavaScript and XML) AJAX uses a combination of : DOM XMLHttpRequest XML is sometimes used as the format for transferring data between the server and client, although any format will work
  • 38. How it work Request process can be handled asynchronously Then a SMALL portion of desired results can be loaded upon completion
  • 39. Make request Create XMLHttpRequest Object - Internet Exployer 5, 6: new ActiveXObject(&quot;Microsoft.XMLHTTP&quot;); - IE7+, Firefox, Chrome, Opera, Safari : new XMLHttpRequest(); Establishing a Connection : GET or POST request // Open the socket ajx.open(&quot;GET&quot;, &quot;/some/url&quot;, true); // Establish the connection to the server ajx.send();
  • 40. Send data Serializing Data: function User() { name: &quot;John&quot;, last: &quot;Resig&quot; } // Serialized form serObj = name=John&last=Resig Request method : GET ajx.open(&quot;GET&quot;, &quot;/some/url?&quot; + serObj , true); ajx.send(); Request method : POST ajx.open(&quot;POST&quot;, &quot;/some/url&quot;, true); ajx. setRequestHeader ( &quot;Content-Type&quot;, &quot; application/x-www-form-urlencoded &quot;); ajx.send( serObj );
  • 41. Handle response readyState property : request lifecycle 0 : uninitialized 1 : connection establised 2 : request received 3 : processing 4 : finished onreadystatechange property Successful response codes: 200 <= ajx.status < 300 Not modified response : 304 (Safari : undefined) Every other codes will be considered error
  • 42. Update UI Reading the Resulting Data responseXML : This property will contain a reference to a precomputed DOM document responseText : This property contains a reference to the raw text string of data returned by the server ajx.onreadystatechange = function(){ if ( ajx.readyState == 4 ) { if ( ajx.status >= 200 && ajx.status < 300 ) { var scores = document.getElementById(&quot;testDiv&quot;); scores.innerText = ajx. responseText ; } } }; Example http://www.learn-ajax-tutorial.com/
  • 44. Some tips DOM access : Interaction with the DOM is usually slower than normal JavaScript code for-in loops : most JS environments have slow implementation eval and Function constructor : avoid using because overhead is involved in script evaluation //expensive operations var func = new Function(“alert('test')”); Pass functions , not strings, to setTimeout () and setInterval () http://wiki.forum.nokia.com/index.php/JavaScript_Performance_Best_Practices