1 / 30

DOM

DOM. Photo from http://www.flickr.com/photos/emraya/2861149369/. Documents as Objects. DOM. When a browser reads an HTML file, it must interpret the file and render it onscreen. This process is sophisticated.

lani-wade
Download Presentation

DOM

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. DOM Photo from http://www.flickr.com/photos/emraya/2861149369/ Documents as Objects

  2. DOM • When a browser reads an HTML file, it must interpret the file and render it onscreen. This process is sophisticated. • The HTML file is turned into a "tree" object. This object is named 'document' and it is a DOM instance. graphics from Yahoos Douglas Crockford.

  3. DOM • The DOM is a model of the HTML document. • Standardized by w3c • A definition of the objects and supported methods • Standards • DOM 0 is supported by all JavaScript enabled browsers but has no specification. • DOM 1 was released in 1998 • DOM 2 was released in 2000 • DOM 3 is the latest approved standard

  4. DOM • Why the DOM? • Since the HTML file is an 'object', it can be processed and changed by JavaScript functions. This supports user interaction with a web page. • "Dynamic HTML" is a term used by some vendors to describe the combination of HTML, style sheets and scripts that allows documents to be animated. graphics from Yahoos Douglas Crockford.

  5. Overview document document. documentElement document.body The DOM specifies that a variable named "document" is globally accessible. This variable has certain attributes. graphics from Yahoos Douglas Crockford.

  6. Elements and Tree Structure

  7. Elements and Tree Structure

  8. Elements and Tree Structure

  9. DOM Examples • Write a function to give all the siblings that follow an element • Write a function to give all of the children of an element • Write a function to give all of the ancestors of an element.

  10. Walk the DOM • Given this structure, we can write code to walk the DOM and process each node function walkTheDOM(node, func) { func(node); node = node.firstChild; while (node) { walkTheDOM(node, func); node = node.nextSibling; } }

  11. Methods • Find/Get elements • document.getElementById(id) • document.getElementsByTagName(tag) • var item = document.getElementById('x'); • var items = document.getElementsByTagName('img'); • Create elements • document.createElement(tag) • varnewImg = document.createElement('img'); • varnewSpan = document.createElement('span'); • document.createTextNode(text) • varnewText = document.createTextNode('Hello');

  12. Attributes • HTML nodes have attributes. Examples include • style • class • id • Methods to handle attributes • x.setAttribute('id', 'x'); • x.setAttribute('class', 'active lg'); • var id = x.getAttribute('id'); • var classes = x.getAttribute('class');

  13. Affecting Style • Style is an attribute that is an object. This makes things trickier • x.setAttribute('style', 'color:red;border:1px solid black'); • var style = x.getAttribute('style'); • There is a shorthand way to deal with specific CSS properties. • x.style.color = 'red'; • x.style.border= '1px solid black'; • Why doesn't the following work? • x.style.background-color = 'red';

  14. Name differences with Styling • CSS • background-color • border-radius • font-size • list-style-type • word-spacing • z-index • JavaScript • backgroundColor • borderRadius • fontSize • listStyleType • wordSpacing • zIndex

  15. Adding/Deleting Nodes • Newly created nodes are not part of the document. They have simply been created. These methods put nodes into the document • node.appendChild(newNode) • node.insertBefore(newNode, newNodesSibling) • How to replace a child node on a node? • node.parentNode.replaceChild(newNode, node) • How to delete a node in the DOM • node.removeNode(childNodeToRemove) • It is often helpful to take a chunk of HTML and replace it by some other chunk of HTML. This can be done by • node.innerHTML = newHTMLtext.

  16. Events and Handling • An event is a user-generated or a browser-generated action. Events are of specific types. • A handler is a JavaScript function that is called when a specific type of event occurs • Events can be generated by most element nodes • Mouse events • Keyboard events • HTML frame/object events • HTML form events • User interface events • Mutation events (changes to the structure of a document)

  17. Mouse Events • Events related to mouse actions are listed below. Handlers are set up to respond to these events either in HTML or by JavaScript. • <div onclick="mouseClicked()">Push</div> • element.addEventListener('click', mouseClicked);

  18. Creating a page • Write a web page that turns a JavaScript array of NFL teams into an ordered list of HTML strings on the page. • An NFL team has properties • name : a string • city : a string • conference : NFC, AFC • division : EAST, WEST, CENTRAL • Modify to order by conference • Modify to order by division

  19. HTML Form Events http://en.wikipedia.org/wiki/DOM_events

  20. Registering Event Handlers • Elements may cause events when they are acted upon. • Clicking on a button • Clicking on a link • Hovering over an image • There are three techniques for associating a handler with an event. • Works Everywhere: node["on" + type] = handlerFunction; • MS: node.attachEvent("on" + type, handlerFunction); • W3C (NOT MS): node.addEventListener(type, f, false); • The handlerFunction will be sent an event object that describes the event that the handler is responding to. • Except that IE sets a global event variable that must be grabbed.

  21. Event Handling • The node where the event is created is called the target node • The first phase is the capturing phase • Events begin at the root and move toward the target node • Registered and enabled event handlers at nodes along the way are run • The second phase is at the target node • If there are registered handlers there for the event, they are run • The third phase is the bubbling phase • Event goes back to the root; all registered and enabled handlers are run • Once the third phase is complete, the browser will invoke default handling if applicable.

  22. Events • Not all events bubble (e.g., load and unload) • Any handler can stop further event propagation by calling the stopPropagation method of the Event object • Any handler can prevent the default event handler from being executed by calling preventDefault. • Might want to stop a form from being submitted, for example, if a validation error is detected.

  23. DOM 2 • A temporary handler can be created by registering it and then unregistering it with removeEventListener • The currentTarget property of Event always references the object on which the handler is being executed • The MouseEvent interface (a subinterface of Event) has two properties, clientX and clientY, that have the x and y coordinates of the mouse cursor, relative to the upper left corner of the browser window

  24. Registering Handlers • The supported attributes of a DOM element determine what events the element can respond to • The attribute can be directly set to a script (using a script). <head> <script type="text/javascript"> function helloWorld() { window.alert( "Hello World" ); } window.onload = helloWorld; // register a handler document.onclick = helloWorld; // register a handler document.onclick = null; // remove a handler </script> </head> <body> <p>Hello World!</p> </body>

  25. Registering Handlers • Elements can also have the handler specified via HTML • <element onclick=“dothis()” /> • Write an HTML page that contains text elements. Whenever the user clicks on a text element, the background color of that element changes to a randomly determined value. As an added feature – have some text elements jump around on the screen when clicked in addition to changing their color

  26. DOM Events Example • Develop an HTML page that allows users to order a pizza. Use ‘onclick’ handling for the radio buttons • Users must select one topping • Sardines • Anchovies • Lemons • Pumpernickel • Users must select one cheese • Provolone • American • Blue • Cheddar • Some combinations of topping/cheese are so repugnant that it would be unethical to sell them. Users receive a warning if selecting unethical combinations. The selection is nonetheless allowed on the page. • Sardines and Cheddar • Pumpernickel and Blue • Lemons and Blue • Alternately, warn and disallow unethical combinations

  27. JavaScript Dom Methods • alert(text) • confirm(text) • prompt(text, default) • These functions block. • Avoid these in Ajax applications. • setTimeout(func, msec) • setInterval(func, msec)

  28. The Window • The window object is a JavaScript global object. • Every window, frame, and iframe has its own unique window object. • aka self. And sometimes parent and top.

  29. Browser Detection • How to determine what kind of browser that page is running in. • navigator.userAgent Mozilla/4.0 • http://www.mozilla.org/docs/web-developer/sniffer/browser_type.html • Not really reliable since browsers lie about who they are. • Don't right code that relies on a particular browser. • Rather use feature detection.

  30. Feature Detection • Using reflection, ask if desired features are present. • function addEventHandler(node, type, f) { • if (node.addEventListener) { • node.addEventListener(type, f, false); • } else if (node.attachEvent) { • node.attachEvent("on" + type, f); • } else { • node["on" + type] = f; • } • }

More Related