JavaScript can dynamically manipulate the content, structure, and styling of an HTML document through the Document Object Model (DOM). The DOM represents an HTML document as nodes that can be accessed and modified with JavaScript. Common tasks include dynamically creating and adding elements, handling user events like clicks, and updating content by accessing DOM elements by their id or other attributes.
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>
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
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