SlideShare uma empresa Scribd logo
1 de 33
Baixar para ler offline
JavaScript DOM
                               API
                Rajat Pandit (rajat_pandit@ipcmedia.com)




Thursday, September 24, 2009                               1
Document Object Model
                           W3C thought it was a good idea to keep
                           the DOM API similar across languages
                           Vague specifications meant different
                           implementations across different
                           browsers
                           It became important to know the
                           difference between browsers to make
                           code work across different browsers
                           That didn’t turn out as expected


Thursday, September 24, 2009                                        2
DOM API in
                               JavaScript


Thursday, September 24, 2009                3
Finding Elements
                           DOM API provides for the following
                           methods
                               document.getElementById(id) - Gets
                               element by its id
                               document.getElementsByTagName(tagname)
                               - Get all the elements matching
                               tagname
                               document.getElementsByClassName(class)
                               - Currently only support by Firefox :(



Thursday, September 24, 2009                                            4
Modifying Elements
                           Old School Method (smaller &
                           faster)
                         if (my_image.complete) {
                                my_image.src = support_url;
                         }


                           W3C way of changing attributes.
                          if (my_image.getAttribute('complete')) {
                          	 my_image.setAttribute('src',url);
                          }




Thursday, September 24, 2009                                         5
Changing style of elements
                           node.className
                           node.style.stylename
                           node.currentStyle.stylename

                           Only supported by IE so far,
                           reports back the computed
                           style, similar to firebug


Thursday, September 24, 2009                              6
Style Names (css/js)
                        css style name           javascript
                     background-color            equivalent
                                              backgroundColor
                          border-radius        borderRadius
                                font-size        fontSize
                       list-style-type         listStyleType
                               word-spacing     wordSpacing
                                 z-index          zIndex



Thursday, September 24, 2009                                    7
Making New Elements
                           DOM allows you to create new elements
                           document.createElement(nodename) - creates a
                           new node element
                           document.createTextNode(text) - creates the
                           node of type #text
                           node.cloneNode(boolean) - clones the node
                           and creates a new instance, when set to
                           true, clones all its decendents a well.
                           Important thing to remember is, the new
                           nodes are not attached to the DOM



Thursday, September 24, 2009                                              8
Linking Elements to a parent
                           node.appendChild(new_node) - attaches
                           new_node to node as a descendent
                           node.insertBefore(new_node, sibling) - adds
                           new_node before the sibling node (pretty odd)
                           node.replaceChild(new, old) - replaces old
                           node with the new node
                           better written as
                           old.parentNode.replaceChild(new, old)
                           Very odd that all methods require link to the
                           parent node



Thursday, September 24, 2009                                               9
Removing Nodes
                           Removing nodes is even weirder
                           node.removeChild(old) - how odd!!
                           better written as
                           old.parentNode.removeChild(old)
                               I call it the suicide method




Thursday, September 24, 2009                                   10
innerHTML
                           Not part of the original W3C spec
                           added by IE and now all a-grade
                           browsers support it
                           You can do the same by appendChild but
                           it can be really complex for bigger
                           structures
                           Which option is better? readability and
                           clean code should always take a higher
                           priority when taking that decision



Thursday, September 24, 2009                                         11
Event Model
                           The browser has an event
                           driven single treaded,
                           asynchronous programming model
                           Events are targeted at
                           particular nodes
                           Events cause the invocation of
                           event handlers


Thursday, September 24, 2009                                12
Mouse Events
                           The target is the topmost (z-index) node
                           containing the cursor
                               click
                               dblclick
                               mousedown
                               mousemove
                               mouseout
                               mouseover
                               mouseup



Thursday, September 24, 2009                                          13
Input Events
                           The target is the node having focus
                               blur
                               change
                               focus
                               keydown
                               keypress
                               keyup
                               reset
                               submit



Thursday, September 24, 2009                                     14
Attaching Event Handlers
                       Classic Method (still works)
                         node[“on” + type] = f
                       W3C Way
                               node.addEventListener(type, f, false)

                       MS Way (Why not!!)
                               node.attachEvent(“on”+type, f)




Thursday, September 24, 2009                                           15
Event Handlers
                           The handler takes an optional event parameter
                           MS doesn’t send an event param to the handler,
                           use the global event object instead. Screws up
                           meaning of “this” object

                       function(e) {
                           e = e || event;
                           var target =
                               e.target || e.srcElement;
                               // more code.
                       }




Thursday, September 24, 2009                                                16
Event Dispatching
                           Trickling - is an event capturing
                           pattern which provides compatibility
                           with NS4. Track event at the top and
                           work the way down till it finds the
                           node. Crazy Idea, avoid it!!
                           Bubbling - Event is given to an element
                           and passes on to its parent and then
                           its parent or so until it’s cancelled.




Thursday, September 24, 2009                                         17
Event Dispatching
                           Trickling - is an event capturing
                           pattern which provides compatibility
                           with NS4. Track event at the top and
                           work the way down till it finds the
                           node. Crazy Idea, avoid it!!
                           Bubbling - Event is given to an element
                           and passes on to its parent and then
                           its parent or so until it’s cancelled.
                                MS got this one right



Thursday, September 24, 2009                                         17
Why Bubble?
                           Assume a case of 100
                           draggable objects
                           Attach 100 event handlers,one
                           to each object
                           or attach 1 Event handler to
                           the container and find out
                           the target from there instead


Thursday, September 24, 2009                               18
Cancel Bubbling
                           Cancel bubbling to keep the
                           parent nodes from seeing the
                           event
                        e.cancelBubble = true; // IE
                        if (e.stopPropogation) {
                             e.stopPropogation();
                        }




Thursday, September 24, 2009                              19
Prevent Default Action
                           An event handler can prevent
                           browser action associated with
                           the event (such as submitting the
                           form)
                       e.returnValue = false;
                       if (e.preventDefault) {
                                e.preventDefault();
                       }
                       return false;




Thursday, September 24, 2009                                   20
Memory Management
                           Usually gc algo on most browsers is pretty good
                           Always a good idea to set null to a variable when
                           no longer is used
                           IE 6 Memory leak issue (make sure you remove
                           event handlers before removing an element)
                           IE6 uses reference counting garbage collector
                           algo (+1 for reference, -1 when set to null when
                           zero its garbaged collected)
                           reference counting is not able to reclaim cyclic
                           structure
                           these cycles need to be broken manually




Thursday, September 24, 2009                                                   21
Memory Leaks on IE6
                           Not an issue for page view driven
                           applications
                           but a show stopper for AJAX Applications
                           Now fixed in IE7
                           Remove all event handlers from elements due
                           to be deleted
                           Must be done for nodes before removeChild /
                           replaceChild
                           It must be done on nodes before they are
                           replaced by innerHTML



Thursday, September 24, 2009                                             22
Memory Leaks in IE6
                           You can use YUI’s
                           purgeElement method or
                      function purgeEventHandlers(node) {
                        for(var n in node) {
                          if (typeof node[n] === ‘function’) {
                            node[n] = null;
                          }
                        }
                      }




Thursday, September 24, 2009                                     23
More JavaScript Elements
                           These are assumed to be part of JavaScript
                           but actually provided by DOM
                               alert(text)
                               confirm(text)
                               prompt(text, default_value)
                               Don’t use these for AJAX apps as they break
                               the async form, use YUI dialogues instead
                           setTimeout(func, msec)
                           setInterval(func, msec)




Thursday, September 24, 2009                                                 24
window object
                           The window object is the
                           javascript global object
                           It’s the meeting point between
                           JS/DOM
                           Every window, frame, iframe
                           has its own window object
                           AKA self


Thursday, September 24, 2009                                25
Inter-window communication
                           frame[] - child frames and iframes
                           name - text name for the window
                           opener - reference to the opener of current
                           window object
                           parent - reference to the parent
                           self - reference to this window
                           top - reference to the outermost window
                           window - reference to the current window
                           open() - opens a new window



Thursday, September 24, 2009                                             26
More on inter-window
                                      communication
                           A script can access another window if it
                           can get a reference to it

                        document.domain = otherwindow.document.domain


                           Same Origin Policy
                               Workaround, if a.b.com needs to talk to
                               c.b.com set

                               document.domain = c.b.com




Thursday, September 24, 2009                                             27
Cross Browser Issues
                           Weak standards result in significant vendor
                           specific differences between the browsers
                           There are three ways of resolving it
                               Browser Detection - worked well when there
                               were only a few browsers to support
                               Feature Detection - By far the safest way,
                               check if the value exists before you use
                               it
                               Platform Libraries - Use MS Atlas or
                               Yahoo! YUI



Thursday, September 24, 2009                                                28
Coping
                           Do what works
                           Do what is common
                           Do what is standard (sad this
                           is not #1)




Thursday, September 24, 2009                               29
The limiting Factor
                           Browsers are being pushed to
                           their limits
                           Be prepared to back off
                           Reduce memory requirements
                           Balance client and server
                           actions (don’t try and do
                           everything on client side)


Thursday, September 24, 2009                              30
What to watch out for?
                           Browsers weren’t designed to be a general
                           purpose application (newer versions are
                           doing that, chrome is the right direction)
                           Lacks a compositing model - new elements
                           can’t be made with current elements,
                           visually yes but browsers/screen readers
                           still see them as individual elements
                           Lacks support for co-operation under mutual
                           suspicion (mashups need to be written extra
                           carefully to ensure there is no clobbering)



Thursday, September 24, 2009                                             31
Resources
                           DOM Cheat Sheet By Christian
                               http://www.wait-till-i.com/2007/06/27/dom-
                               javascript-cheat-sheet/


                           Mozilla’s take on DOM
                               https://developer.mozilla.org/en/DOM


                           Convert Markup to DOM methods
                               http://muffinresearch.co.uk/code/javascript/
                               DOMTool/




Thursday, September 24, 2009                                                  32

Mais conteúdo relacionado

Destaque

JavaScript DOM Manipulations
JavaScript DOM ManipulationsJavaScript DOM Manipulations
JavaScript DOM ManipulationsYnon Perek
 
JavaScript Library Overview
JavaScript Library OverviewJavaScript Library Overview
JavaScript Library Overviewjeresig
 
DIWE - Programming with JavaScript
DIWE - Programming with JavaScriptDIWE - Programming with JavaScript
DIWE - Programming with JavaScriptRasan Samarasinghe
 
Le Wagon - Javascript for Beginners
Le Wagon - Javascript for BeginnersLe Wagon - Javascript for Beginners
Le Wagon - Javascript for BeginnersSébastien Saunier
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Aaron Gustafson
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to JavascriptAmit Tyagi
 
Unobtrusive JavaScript with jQuery
Unobtrusive JavaScript with jQueryUnobtrusive JavaScript with jQuery
Unobtrusive JavaScript with jQuerySimon Willison
 
Maintainable JavaScript 2012
Maintainable JavaScript 2012Maintainable JavaScript 2012
Maintainable JavaScript 2012Nicholas Zakas
 
Writing Efficient JavaScript
Writing Efficient JavaScriptWriting Efficient JavaScript
Writing Efficient JavaScriptNicholas Zakas
 

Destaque (13)

Powershell Certificate
Powershell CertificatePowershell Certificate
Powershell Certificate
 
Java script for web developer
Java script for web developerJava script for web developer
Java script for web developer
 
JavaScript
JavaScriptJavaScript
JavaScript
 
JavaScript DOM Manipulations
JavaScript DOM ManipulationsJavaScript DOM Manipulations
JavaScript DOM Manipulations
 
JavaScript Library Overview
JavaScript Library OverviewJavaScript Library Overview
JavaScript Library Overview
 
Javascript and DOM
Javascript and DOMJavascript and DOM
Javascript and DOM
 
DIWE - Programming with JavaScript
DIWE - Programming with JavaScriptDIWE - Programming with JavaScript
DIWE - Programming with JavaScript
 
Le Wagon - Javascript for Beginners
Le Wagon - Javascript for BeginnersLe Wagon - Javascript for Beginners
Le Wagon - Javascript for Beginners
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Unobtrusive JavaScript with jQuery
Unobtrusive JavaScript with jQueryUnobtrusive JavaScript with jQuery
Unobtrusive JavaScript with jQuery
 
Maintainable JavaScript 2012
Maintainable JavaScript 2012Maintainable JavaScript 2012
Maintainable JavaScript 2012
 
Writing Efficient JavaScript
Writing Efficient JavaScriptWriting Efficient JavaScript
Writing Efficient JavaScript
 

Semelhante a Dom API In Java Script

Advanced Node.JS Meetup
Advanced Node.JS MeetupAdvanced Node.JS Meetup
Advanced Node.JS MeetupLINAGORA
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Domkaven yan
 
Building businesspost.ie using Node.js
Building businesspost.ie using Node.jsBuilding businesspost.ie using Node.js
Building businesspost.ie using Node.jsRichard Rodger
 
Node js presentation
Node js presentationNode js presentation
Node js presentationshereefsakr
 
MvvmCross Introduction
MvvmCross IntroductionMvvmCross Introduction
MvvmCross IntroductionStuart Lodge
 
MvvmCross Seminar
MvvmCross SeminarMvvmCross Seminar
MvvmCross SeminarXamarin
 
Testing Apache Modules with Python and Ctypes
Testing Apache Modules with Python and CtypesTesting Apache Modules with Python and Ctypes
Testing Apache Modules with Python and CtypesMarkus Litz
 
Exploring Next Generation Buildpacks - Anand Rao & Scott Deeg
Exploring Next Generation Buildpacks - Anand Rao & Scott DeegExploring Next Generation Buildpacks - Anand Rao & Scott Deeg
Exploring Next Generation Buildpacks - Anand Rao & Scott DeegVMware Tanzu
 
- Codemotion Rome 2015
- Codemotion Rome 2015- Codemotion Rome 2015
- Codemotion Rome 2015Codemotion
 
Gentle Intro to Drupal Code
Gentle Intro to Drupal CodeGentle Intro to Drupal Code
Gentle Intro to Drupal CodeAddison Berry
 
Mac ruby deployment
Mac ruby deploymentMac ruby deployment
Mac ruby deploymentThilo Utke
 
A brief overview of java frameworks
A brief overview of java frameworksA brief overview of java frameworks
A brief overview of java frameworksMD Sayem Ahmed
 
Bringing the light to the client with KnockoutJS
Bringing the light to the client with KnockoutJSBringing the light to the client with KnockoutJS
Bringing the light to the client with KnockoutJSBoyan Mihaylov
 

Semelhante a Dom API In Java Script (20)

Advanced Node.JS Meetup
Advanced Node.JS MeetupAdvanced Node.JS Meetup
Advanced Node.JS Meetup
 
The Theory Of The Dom
The Theory Of The DomThe Theory Of The Dom
The Theory Of The Dom
 
Building businesspost.ie using Node.js
Building businesspost.ie using Node.jsBuilding businesspost.ie using Node.js
Building businesspost.ie using Node.js
 
Node js presentation
Node js presentationNode js presentation
Node js presentation
 
MvvmCross Introduction
MvvmCross IntroductionMvvmCross Introduction
MvvmCross Introduction
 
MvvmCross Seminar
MvvmCross SeminarMvvmCross Seminar
MvvmCross Seminar
 
201005 accelerometer and core Location
201005 accelerometer and core Location201005 accelerometer and core Location
201005 accelerometer and core Location
 
Testing Apache Modules with Python and Ctypes
Testing Apache Modules with Python and CtypesTesting Apache Modules with Python and Ctypes
Testing Apache Modules with Python and Ctypes
 
imgproxy is amazing
imgproxy is amazingimgproxy is amazing
imgproxy is amazing
 
Plone pwns
Plone pwnsPlone pwns
Plone pwns
 
Exploring Next Generation Buildpacks - Anand Rao & Scott Deeg
Exploring Next Generation Buildpacks - Anand Rao & Scott DeegExploring Next Generation Buildpacks - Anand Rao & Scott Deeg
Exploring Next Generation Buildpacks - Anand Rao & Scott Deeg
 
- Codemotion Rome 2015
- Codemotion Rome 2015- Codemotion Rome 2015
- Codemotion Rome 2015
 
Stephanie Rewis - css-startech
Stephanie Rewis -  css-startechStephanie Rewis -  css-startech
Stephanie Rewis - css-startech
 
Gentle Intro to Drupal Code
Gentle Intro to Drupal CodeGentle Intro to Drupal Code
Gentle Intro to Drupal Code
 
13488117.ppt
13488117.ppt13488117.ppt
13488117.ppt
 
13488117.ppt
13488117.ppt13488117.ppt
13488117.ppt
 
Jclouds Introduction
Jclouds IntroductionJclouds Introduction
Jclouds Introduction
 
Mac ruby deployment
Mac ruby deploymentMac ruby deployment
Mac ruby deployment
 
A brief overview of java frameworks
A brief overview of java frameworksA brief overview of java frameworks
A brief overview of java frameworks
 
Bringing the light to the client with KnockoutJS
Bringing the light to the client with KnockoutJSBringing the light to the client with KnockoutJS
Bringing the light to the client with KnockoutJS
 

Último

Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 

Último (20)

Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 

Dom API In Java Script

  • 1. JavaScript DOM API Rajat Pandit (rajat_pandit@ipcmedia.com) Thursday, September 24, 2009 1
  • 2. Document Object Model W3C thought it was a good idea to keep the DOM API similar across languages Vague specifications meant different implementations across different browsers It became important to know the difference between browsers to make code work across different browsers That didn’t turn out as expected Thursday, September 24, 2009 2
  • 3. DOM API in JavaScript Thursday, September 24, 2009 3
  • 4. Finding Elements DOM API provides for the following methods document.getElementById(id) - Gets element by its id document.getElementsByTagName(tagname) - Get all the elements matching tagname document.getElementsByClassName(class) - Currently only support by Firefox :( Thursday, September 24, 2009 4
  • 5. Modifying Elements Old School Method (smaller & faster) if (my_image.complete) { my_image.src = support_url; } W3C way of changing attributes. if (my_image.getAttribute('complete')) { my_image.setAttribute('src',url); } Thursday, September 24, 2009 5
  • 6. Changing style of elements node.className node.style.stylename node.currentStyle.stylename Only supported by IE so far, reports back the computed style, similar to firebug Thursday, September 24, 2009 6
  • 7. Style Names (css/js) css style name javascript background-color equivalent backgroundColor border-radius borderRadius font-size fontSize list-style-type listStyleType word-spacing wordSpacing z-index zIndex Thursday, September 24, 2009 7
  • 8. Making New Elements DOM allows you to create new elements document.createElement(nodename) - creates a new node element document.createTextNode(text) - creates the node of type #text node.cloneNode(boolean) - clones the node and creates a new instance, when set to true, clones all its decendents a well. Important thing to remember is, the new nodes are not attached to the DOM Thursday, September 24, 2009 8
  • 9. Linking Elements to a parent node.appendChild(new_node) - attaches new_node to node as a descendent node.insertBefore(new_node, sibling) - adds new_node before the sibling node (pretty odd) node.replaceChild(new, old) - replaces old node with the new node better written as old.parentNode.replaceChild(new, old) Very odd that all methods require link to the parent node Thursday, September 24, 2009 9
  • 10. Removing Nodes Removing nodes is even weirder node.removeChild(old) - how odd!! better written as old.parentNode.removeChild(old) I call it the suicide method Thursday, September 24, 2009 10
  • 11. innerHTML Not part of the original W3C spec added by IE and now all a-grade browsers support it You can do the same by appendChild but it can be really complex for bigger structures Which option is better? readability and clean code should always take a higher priority when taking that decision Thursday, September 24, 2009 11
  • 12. Event Model The browser has an event driven single treaded, asynchronous programming model Events are targeted at particular nodes Events cause the invocation of event handlers Thursday, September 24, 2009 12
  • 13. Mouse Events The target is the topmost (z-index) node containing the cursor click dblclick mousedown mousemove mouseout mouseover mouseup Thursday, September 24, 2009 13
  • 14. Input Events The target is the node having focus blur change focus keydown keypress keyup reset submit Thursday, September 24, 2009 14
  • 15. Attaching Event Handlers Classic Method (still works) node[“on” + type] = f W3C Way node.addEventListener(type, f, false) MS Way (Why not!!) node.attachEvent(“on”+type, f) Thursday, September 24, 2009 15
  • 16. Event Handlers The handler takes an optional event parameter MS doesn’t send an event param to the handler, use the global event object instead. Screws up meaning of “this” object function(e) { e = e || event; var target = e.target || e.srcElement; // more code. } Thursday, September 24, 2009 16
  • 17. Event Dispatching Trickling - is an event capturing pattern which provides compatibility with NS4. Track event at the top and work the way down till it finds the node. Crazy Idea, avoid it!! Bubbling - Event is given to an element and passes on to its parent and then its parent or so until it’s cancelled. Thursday, September 24, 2009 17
  • 18. Event Dispatching Trickling - is an event capturing pattern which provides compatibility with NS4. Track event at the top and work the way down till it finds the node. Crazy Idea, avoid it!! Bubbling - Event is given to an element and passes on to its parent and then its parent or so until it’s cancelled. MS got this one right Thursday, September 24, 2009 17
  • 19. Why Bubble? Assume a case of 100 draggable objects Attach 100 event handlers,one to each object or attach 1 Event handler to the container and find out the target from there instead Thursday, September 24, 2009 18
  • 20. Cancel Bubbling Cancel bubbling to keep the parent nodes from seeing the event e.cancelBubble = true; // IE if (e.stopPropogation) { e.stopPropogation(); } Thursday, September 24, 2009 19
  • 21. Prevent Default Action An event handler can prevent browser action associated with the event (such as submitting the form) e.returnValue = false; if (e.preventDefault) { e.preventDefault(); } return false; Thursday, September 24, 2009 20
  • 22. Memory Management Usually gc algo on most browsers is pretty good Always a good idea to set null to a variable when no longer is used IE 6 Memory leak issue (make sure you remove event handlers before removing an element) IE6 uses reference counting garbage collector algo (+1 for reference, -1 when set to null when zero its garbaged collected) reference counting is not able to reclaim cyclic structure these cycles need to be broken manually Thursday, September 24, 2009 21
  • 23. Memory Leaks on IE6 Not an issue for page view driven applications but a show stopper for AJAX Applications Now fixed in IE7 Remove all event handlers from elements due to be deleted Must be done for nodes before removeChild / replaceChild It must be done on nodes before they are replaced by innerHTML Thursday, September 24, 2009 22
  • 24. Memory Leaks in IE6 You can use YUI’s purgeElement method or function purgeEventHandlers(node) { for(var n in node) { if (typeof node[n] === ‘function’) { node[n] = null; } } } Thursday, September 24, 2009 23
  • 25. More JavaScript Elements These are assumed to be part of JavaScript but actually provided by DOM alert(text) confirm(text) prompt(text, default_value) Don’t use these for AJAX apps as they break the async form, use YUI dialogues instead setTimeout(func, msec) setInterval(func, msec) Thursday, September 24, 2009 24
  • 26. window object The window object is the javascript global object It’s the meeting point between JS/DOM Every window, frame, iframe has its own window object AKA self Thursday, September 24, 2009 25
  • 27. Inter-window communication frame[] - child frames and iframes name - text name for the window opener - reference to the opener of current window object parent - reference to the parent self - reference to this window top - reference to the outermost window window - reference to the current window open() - opens a new window Thursday, September 24, 2009 26
  • 28. More on inter-window communication A script can access another window if it can get a reference to it document.domain = otherwindow.document.domain Same Origin Policy Workaround, if a.b.com needs to talk to c.b.com set document.domain = c.b.com Thursday, September 24, 2009 27
  • 29. Cross Browser Issues Weak standards result in significant vendor specific differences between the browsers There are three ways of resolving it Browser Detection - worked well when there were only a few browsers to support Feature Detection - By far the safest way, check if the value exists before you use it Platform Libraries - Use MS Atlas or Yahoo! YUI Thursday, September 24, 2009 28
  • 30. Coping Do what works Do what is common Do what is standard (sad this is not #1) Thursday, September 24, 2009 29
  • 31. The limiting Factor Browsers are being pushed to their limits Be prepared to back off Reduce memory requirements Balance client and server actions (don’t try and do everything on client side) Thursday, September 24, 2009 30
  • 32. What to watch out for? Browsers weren’t designed to be a general purpose application (newer versions are doing that, chrome is the right direction) Lacks a compositing model - new elements can’t be made with current elements, visually yes but browsers/screen readers still see them as individual elements Lacks support for co-operation under mutual suspicion (mashups need to be written extra carefully to ensure there is no clobbering) Thursday, September 24, 2009 31
  • 33. Resources DOM Cheat Sheet By Christian http://www.wait-till-i.com/2007/06/27/dom- javascript-cheat-sheet/ Mozilla’s take on DOM https://developer.mozilla.org/en/DOM Convert Markup to DOM methods http://muffinresearch.co.uk/code/javascript/ DOMTool/ Thursday, September 24, 2009 32