KEMBAR78
JavaScript & Dom Manipulation | PPT
JavaScript & DOM Manipulation Mohammed Arif Senior Interactive Developer @  SapientNitro Twitter@ arif_iq Linkedin:  http:// in.linkedin.com/in/mohdarif Blog:  http:// www.mohammedarif.com
Agenda: JavaScript As “the Behavior Layer” JavaScript: What it is and isn't ECMAScript JavaScript: Usage Naming conventions What is the DOM?
Before We Start! Important tools to have   Firebug for Firefox ( http:// w ww.getfirebug.com ) IE Web Developer Toolbar (handy) ( http://www.microsoft.com/downloads/details.aspx?familyid=E59C3964-672D-4511-BB3E-2D5E1DB91038&displaylang=en ) DebugBar for IE ( http:// www.debugbar.com/download.php )
JavaScript As “the Behavior Layer”: ‱  The behavior layer :   Is executed on the client and defines how different elements behave when the user interacts with them (JavaScript or ActionScript for Flash sites). ‱  The presentation layer :   Is displayed on the client and is the look of the web page (CSS, imagery).
‱  The structure layer :  Is converted or displayed by the user agent. This is the markup defining what a certain text or media is (XHTML). ‱  The content layer :  Is stored on the server and consists of all the text, images, and multimedia content that are used on the site (XML, database, media assets). ‱  The business logic layer (or back end) :  Runs on the server and determines what is done with incoming data and what gets returned to the user.
JS: What it is and isn’t NOT Java despite its name ECMAScript More than form validation Client-Side Scripting Language Dynamic Object-Based (Prototype-Based) It is an interpreted language
ECMAScript: ECMAScript is a scripting programming language, standardized by ECMA International in the ECMA-262 specification. The language is widely used on the web, and is often referred to as JavaScript or JScript. Each browser has its own implementation of the ECMAScript interface, which is then extended to contain the DOM and BOM. There are other languages that also implement and extend ECMAScript such as Windows Scripting Host (WSH), ActionScript in Macromedia Flash, and Nombas ScriptEase.
JS: Usage Drop this puppy in your page:  <html> <head> <title>Example JS Page</title> <script language=”JavaScript”> <!-- hide from older browsers function sayHi() { alert(“Hi”); } //--> </script> <noscript> <p>Your browser doesn’t support JavaScript. If it did support JavaScript, you would see this message: Hi!</p> </noscript> </head> <body> </body> </html> Example: However, noscript is deprecated in XHTML and strict} HTML, and there is no need for it—if you create JavaScript that is unobtrusive.
Naming conventions Camel Notation  — the first letter is lowercase and each appended word begins with an uppercase letter. For example: var  m y T est V alue = 0,  m y S econd T est V alue = “hi”; Pascal Notation  —the first letter is uppercase and each appended word begins with an uppercase letter. For example: var  M y T est V alue = 0,  M y S econd T est V alue = “hi”; Hungarian Type Notation  — prepends a lowercase letter (or sequence of lowercase letters) to the beginning of a Pascal Notation variable name to indicate the type of the variable. For example, i means integer and s means string in the following line: var  iM y T est V alue = 0,  sM y S econd T est V alue = “hi”;
JS: Literals The following are literals
each variable is literally the data assigned. JavaScript does not have strict data types <script type=“text/javascript”> var myNumber = 123; var myString = ‘Bork!’; var myBoolean = true; var myFunction = function(){ return ‘hello’;} //anonymous function   var myArray = [1, 2, 3]; </script>
Variables Scope There are two types of variables: Local variables  Are created within a function Only recognized within that function Multiple functions can use the same local variable name without error Global variables  Are available everywhere Names must be unique How do you create a local or a global function? Created inside a function: Declared with “var” it’s local Without “var” and it’s global  Created outside of a function, it’s always global
JS: Objects Everything in JS is an Object Those literals can be written: <script type=“text/javascript”> var myNumber = new Number(123); var myString = new String(‘Rayyan’); var myBoolean = new Boolean(true); var myFunction = new Function(‘’, “return ‘hello’”);} var myRegExp = new RegExp(‘bork’); var myArray = new Array(); myArray[0] = 1; myArray[1] = 2; myArray[2] = 3; var myCarObject = new Object(); myCarObject.color = ‘red’; myCarObject.tires = 4; myCarObject.windows = 6; </script>
JS: Control Structures if (condition) { //... }  else  { //... } while (condition) { //... } for (var i = 0; i< 10; i++) { //... } for (var element  in  array_of_elements) { //... } do  { //... }  while (condition); switch (param) { case  1: // if param == 1... case  'whee': // if param == 'whee'... case  false: // if param == false... default : // otherwise ... } try  { //... }  catch (err) { //... }
What is the DOM? The  Document Object Model  (DOM) is an application programming interface (API) for HTML as well as XML. The DOM maps out an entire page as a document composed of a hierarchy of nodes.  It alter the appearance & content of a page without reloading the document. Each part of an HTML or XML page is a derivative of a node. Consider the following HTML page:
DOM == Document Object Model The DOM is hierarchical <html> <head> <title>Example JS Page</title> </head> <body> <div id=“Rayyan”> <ul>   <li>Delhi</li>   <li>Mumbai</li>   <li>Chennai</li>   <li>Kolkata</li> </ul> </div> </body> </html>
DOM Tree:
Finding DOM Elements document.getElementById(id) returns a specific element document.getElementsByTagName(DIV) returns an array of elements document.getElementsByName(name) returns a collection of objects with the specified NAME
DOM Element Attributes nodeName nodeValue nodeType parentNode childNodes firstChild lastChild previousSibling nextSibling attributes ownerDocument 1 = an HTML element 2 = an element attribute 3 = text 8 = an HTML comment 9 = a document 10 = a document type definition DOM Attributes Node Types (12)
Manipulating the DOM Dynamically creating and adding elements document.createElement appendChild
Events Click Dblclick Mousedown Mouseup Mouseover Mousemove Mouseout Keypress Keydown Keyup Select Change Submit Reset Focus Blur Load Unload  Abort Error Resize Scroll Mouse Keyboard Frame/Object Form
Event Handlers/Listeners: With an event handler you can do something with an element when an event occurs: when the user clicks an element, when the page loads, when a form is submitted, etc.  To assign an event handler in JavaScript, you have to get a reference to the object in question and then assign a function to the corresponding event handler property like this: var oDiv = document.getElementById(“div1”); oDiv.onclick = function () { alert(“I was clicked”); }; <div onclick=”alert(‘I was clicked’)”></div> &
Internet Explorer In IE, every element and window object has two methods: attachEvent()  and detachEvent(). var fnClick = function () { alert(“Clicked!”); }; var oDiv = document.getElementById(“div”); oDiv.attachEvent(“onclick”, fnClick); //add the event handler //do some other stuff here oDiv.detachEvent(“onclick”, fnClick); //remove the event handler
DOM (Mozilla, Opera, etc.) The DOM methods addEventListener() and removeEventListener() accomplish the assignment and removal of event handlers. These methods, unlike IE, take three parameters: the event name, the function to assign, and whether the handler should be used for the bubbling or capture phase. If the handler is to be used in the capture phase, the third parameter is true; for the bubbling phase, it is false. Here’s the general syntax: [Object]. addEventListener(“name_of_event”, fnHandler, bCapture); [Object]. removeEventListener(“name_of_event”, fnHandler, bCapture); example
References JavaScript http://www.w3schools.com/JS/default.asp http://www.mozilla.org/js/scripting/ http://www.quirksmode.org/resources.html DOM http://www.w3schools.com/htmldom/ http://www.quirksmode.org/dom/intro.html http://www.javascriptkit.com/domref/ http:// developer.mozilla.org/en/docs/The_DOM_and_JavaScript

JavaScript & Dom Manipulation

  • 1.
    JavaScript & DOMManipulation Mohammed Arif Senior Interactive Developer @ SapientNitro Twitter@ arif_iq Linkedin: http:// in.linkedin.com/in/mohdarif Blog: http:// www.mohammedarif.com
  • 2.
    Agenda: JavaScript As“the Behavior Layer” JavaScript: What it is and isn't ECMAScript JavaScript: Usage Naming conventions What is the DOM?
  • 3.
    Before We Start!Important tools to have Firebug for Firefox ( http:// w ww.getfirebug.com ) IE Web Developer Toolbar (handy) ( http://www.microsoft.com/downloads/details.aspx?familyid=E59C3964-672D-4511-BB3E-2D5E1DB91038&displaylang=en ) DebugBar for IE ( http:// www.debugbar.com/download.php )
  • 4.
    JavaScript As “theBehavior Layer”: ‱ The behavior layer : Is executed on the client and defines how different elements behave when the user interacts with them (JavaScript or ActionScript for Flash sites). ‱ The presentation layer : Is displayed on the client and is the look of the web page (CSS, imagery).
  • 5.
    ‱ Thestructure layer : Is converted or displayed by the user agent. This is the markup defining what a certain text or media is (XHTML). ‱ The content layer : Is stored on the server and consists of all the text, images, and multimedia content that are used on the site (XML, database, media assets). ‱ The business logic layer (or back end) : Runs on the server and determines what is done with incoming data and what gets returned to the user.
  • 6.
    JS: What itis and isn’t NOT Java despite its name ECMAScript More than form validation Client-Side Scripting Language Dynamic Object-Based (Prototype-Based) It is an interpreted language
  • 7.
    ECMAScript: ECMAScript isa scripting programming language, standardized by ECMA International in the ECMA-262 specification. The language is widely used on the web, and is often referred to as JavaScript or JScript. Each browser has its own implementation of the ECMAScript interface, which is then extended to contain the DOM and BOM. There are other languages that also implement and extend ECMAScript such as Windows Scripting Host (WSH), ActionScript in Macromedia Flash, and Nombas ScriptEase.
  • 8.
    JS: Usage Dropthis puppy in your page: <html> <head> <title>Example JS Page</title> <script language=”JavaScript”> <!-- hide from older browsers function sayHi() { alert(“Hi”); } //--> </script> <noscript> <p>Your browser doesn’t support JavaScript. If it did support JavaScript, you would see this message: Hi!</p> </noscript> </head> <body> </body> </html> Example: However, noscript is deprecated in XHTML and strict} HTML, and there is no need for it—if you create JavaScript that is unobtrusive.
  • 9.
    Naming conventions CamelNotation — the first letter is lowercase and each appended word begins with an uppercase letter. For example: var m y T est V alue = 0, m y S econd T est V alue = “hi”; Pascal Notation —the first letter is uppercase and each appended word begins with an uppercase letter. For example: var M y T est V alue = 0, M y S econd T est V alue = “hi”; Hungarian Type Notation — prepends a lowercase letter (or sequence of lowercase letters) to the beginning of a Pascal Notation variable name to indicate the type of the variable. For example, i means integer and s means string in the following line: var iM y T est V alue = 0, sM y S econd T est V alue = “hi”;
  • 10.
    JS: Literals Thefollowing are literals
each variable is literally the data assigned. JavaScript does not have strict data types <script type=“text/javascript”> var myNumber = 123; var myString = ‘Bork!’; var myBoolean = true; var myFunction = function(){ return ‘hello’;} //anonymous function var myArray = [1, 2, 3]; </script>
  • 11.
    Variables Scope Thereare two types of variables: Local variables Are created within a function Only recognized within that function Multiple functions can use the same local variable name without error Global variables Are available everywhere Names must be unique How do you create a local or a global function? Created inside a function: Declared with “var” it’s local Without “var” and it’s global Created outside of a function, it’s always global
  • 12.
    JS: Objects Everythingin JS is an Object Those literals can be written: <script type=“text/javascript”> var myNumber = new Number(123); var myString = new String(‘Rayyan’); var myBoolean = new Boolean(true); var myFunction = new Function(‘’, “return ‘hello’”);} var myRegExp = new RegExp(‘bork’); var myArray = new Array(); myArray[0] = 1; myArray[1] = 2; myArray[2] = 3; var myCarObject = new Object(); myCarObject.color = ‘red’; myCarObject.tires = 4; myCarObject.windows = 6; </script>
  • 13.
    JS: Control Structuresif (condition) { //... } else { //... } while (condition) { //... } for (var i = 0; i< 10; i++) { //... } for (var element in array_of_elements) { //... } do { //... } while (condition); switch (param) { case 1: // if param == 1... case 'whee': // if param == 'whee'... case false: // if param == false... default : // otherwise ... } try { //... } catch (err) { //... }
  • 14.
    What is theDOM? The Document Object Model (DOM) is an application programming interface (API) for HTML as well as XML. The DOM maps out an entire page as a document composed of a hierarchy of nodes. It alter the appearance & content of a page without reloading the document. Each part of an HTML or XML page is a derivative of a node. Consider the following HTML page:
  • 15.
    DOM == DocumentObject Model The DOM is hierarchical <html> <head> <title>Example JS Page</title> </head> <body> <div id=“Rayyan”> <ul> <li>Delhi</li> <li>Mumbai</li> <li>Chennai</li> <li>Kolkata</li> </ul> </div> </body> </html>
  • 16.
  • 17.
    Finding DOM Elementsdocument.getElementById(id) returns a specific element document.getElementsByTagName(DIV) returns an array of elements document.getElementsByName(name) returns a collection of objects with the specified NAME
  • 18.
    DOM Element AttributesnodeName nodeValue nodeType parentNode childNodes firstChild lastChild previousSibling nextSibling attributes ownerDocument 1 = an HTML element 2 = an element attribute 3 = text 8 = an HTML comment 9 = a document 10 = a document type definition DOM Attributes Node Types (12)
  • 19.
    Manipulating the DOMDynamically creating and adding elements document.createElement appendChild
  • 20.
    Events Click DblclickMousedown Mouseup Mouseover Mousemove Mouseout Keypress Keydown Keyup Select Change Submit Reset Focus Blur Load Unload Abort Error Resize Scroll Mouse Keyboard Frame/Object Form
  • 21.
    Event Handlers/Listeners: Withan event handler you can do something with an element when an event occurs: when the user clicks an element, when the page loads, when a form is submitted, etc. To assign an event handler in JavaScript, you have to get a reference to the object in question and then assign a function to the corresponding event handler property like this: var oDiv = document.getElementById(“div1”); oDiv.onclick = function () { alert(“I was clicked”); }; <div onclick=”alert(‘I was clicked’)”></div> &
  • 22.
    Internet Explorer InIE, every element and window object has two methods: attachEvent() and detachEvent(). var fnClick = function () { alert(“Clicked!”); }; var oDiv = document.getElementById(“div”); oDiv.attachEvent(“onclick”, fnClick); //add the event handler //do some other stuff here oDiv.detachEvent(“onclick”, fnClick); //remove the event handler
  • 23.
    DOM (Mozilla, Opera,etc.) The DOM methods addEventListener() and removeEventListener() accomplish the assignment and removal of event handlers. These methods, unlike IE, take three parameters: the event name, the function to assign, and whether the handler should be used for the bubbling or capture phase. If the handler is to be used in the capture phase, the third parameter is true; for the bubbling phase, it is false. Here’s the general syntax: [Object]. addEventListener(“name_of_event”, fnHandler, bCapture); [Object]. removeEventListener(“name_of_event”, fnHandler, bCapture); example
  • 24.
    References JavaScript http://www.w3schools.com/JS/default.asphttp://www.mozilla.org/js/scripting/ http://www.quirksmode.org/resources.html DOM http://www.w3schools.com/htmldom/ http://www.quirksmode.org/dom/intro.html http://www.javascriptkit.com/domref/ http:// developer.mozilla.org/en/docs/The_DOM_and_JavaScript