Upload
borey-lim
View
2.681
Download
7
Embed Size (px)
Citation preview
JavaScript DOM & Event
Open Tech Talk, 22nd January 2011
@HackerSpacePP
var presenter = { name: "Lim Borey", workAt: "Yoolk Inc.", email: "[email protected]", twitter: "@limborey", communities: [ "ShareVisionTeam", "Pailin" ] };
About Me
DOM Overview • DOM: Document Object Model - popular way of
representing XML documents
• Implemented in many languages: o Java,
o Perl,
o PHP,
o Ruby,
o Python,
o JavaScript
o …
• was constructed to provide an intuitive way for
developers to navigate an XML hierarchy
DOM Overview <table border="2"> <tr> <td>cell is row 0 column 0</td> <td>cell is row 0 column 1</td> </tr> <tr> <td>cell is row 1 column 0</td> <td>cell is row 1 column 1</td> </tr> </table>
DOM Overview
Waiting for the HTML DOM to Load
• HTML is parsed.
• External scripts/style sheets are loaded.
• Scripts are executed as they are parsed in the
document.
• HTML DOM is fully constructed.
• Images and external content are loaded.
• The page is finished loading.
Navigating the DOM • The document node
Navigating the DOM <html> <head> <title>JavaScript and DOM Interfaces </title> <script> function start() { myBody = document.getElementsByTagName("body")[0]; myBodyElements = myBody.getElementsByTagName("p"); myP = myBodyElements[1]; } </script> </head> <body onload="start()"> <p>hi</p> <p>hello</p> </body> </html>
Navigating the DOM
Navigating the DOM • All node
Navigating the DOM <p> <strong>Hello</strong> how are you doing? </p>
Creating Node
var textNode = document.createTextNode("world");
var myNewPNode = document.createElement("p");
Attaching, copying or removing nodes
Attaching, copying or removing nodes
myP.appendChild(myTextNode);
Node information
Event • an action that is fired (initiated) within a web page.
• JavaScript is Single Thread
• JavaScript uses asynchronous callback
What you’d see if JavaScript were able to handle threads
A representation of using callbacks to wait for the page to load
Event Phases
Defining Event Handler • Old way
window.onload = init();
• New way (add event)
window.addEventListener("load", init, false);
window.attachEvent("onload", init); //IE
Event Methods • Adding and removing event listener
The Event Object • Contains contextual information about the current
event
• an object that’s provided, or is available, inside of
every event handler function
• W3C Standard Browser: e
• Internet Explorer: window.event
textArea.onkeypress = function(e){ e = e || window.event; return e.keyCode != 13; };
Cancel Bubbling • W3C Standard Browser
e.stopPropagation()
• Internet Explorer
window.event.cancelBubble()
Overriding Browser default event
• W3C Standard Broswer:
e.preventDefault();
• Internet Explorer
window.event.returnValue = false;
References • Pro JavaScript™ Techniques, John Resig
• http://www.howtocreate.co.uk/tutorials/javascript/
domstructure
• https://developer.mozilla.org/en/Traversing_an_HTM
L_table_with_JavaScript_and_DOM_Interfaces