1 The Document Object Model SAMS Teach Yourself JavaScript in 24 Hours (Fourth Edition) Michael Moncur SAMS Publishing 2007.

Slides:



Advertisements
Similar presentations
JavaScript and the DOM Les Carr COMP3001 Les Carr COMP3001.
Advertisements

11 Getting Started with ASP.NET Beginning ASP.NET 4.0 in C# 2010 Chapters 5 and 6.
Tutorial 16 Working with Dynamic Content and Styles.
Chapter 16 Dynamic HTML and Animation The Web Warrior Guide to Web Design Technologies.
 2008 Pearson Education, Inc. All rights reserved Document Object Model (DOM): Objects and Collections.
1 Using jQuery JavaScript & jQuery the missing manual (Second Edition)
CSS (Cascading Style Sheets): How the web is styled Create Rules that specify how the content of an HTML Element should appear. CSS controls how your web.
DHTML - Introduction Introduction to DHTML, the DOM, JS review.
DHTML. What is DHTML?  DHTML is the combination of several built-in browser features in fourth generation browsers that enable a web page to be more.
JavaScript & jQuery the missing manual Chapter 11
HTML DOM.  The HTML DOM defines a standard way for accessing and manipulating HTML documents.  The DOM presents an HTML document as a tree- structure.
JS: Document Object Model (DOM)
 2008 Pearson Education, Inc. All rights reserved Document Object Model (DOM): Objects and Collections.
Amber Annett David Bell October 13 th, What will happen What is this business about personal web pages? Designated location of your own web page.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6 Dynamic Documents With JavaScript.
JavaScript & DOM Client-side scripting. JavaScript JavaScript is a tool to automate client side (which is implemented using HTML so far) JavaSript syntax.
UFCEWT-20-3 Advanced Topics in Web Development Lecture 4 : JavaScript, Browsers & the HTML DOM-API.
DOM and JavaScript Aryo Pinandito.
Lecture 11 – DOM Scripting SFDV3011 – Advanced Web Development Reference: 1.
D2L Notes Be sure to submit your link in the dropbox provided on D2L You can just upload an empty text file if a file upload is required Do not use D2L.
CSS Class 7 Add JavaScript to your page Add event handlers Validate a form Open a new window Hide and show elements Swap images Debug JavaScript.
Website Development with Dreamweaver
CITS1231 Web Technologies JavaScript and Document Object Model.
Lesson13. JavaScript JavaScript is an interpreted language, designed to function within a web browser. It can also be used on the server.
JavaScript – The DOM JavaScript is object based The browser is object based – We can access the browser's objects in the same way we did JavaScript's Two.
JavaScript, Fourth Edition
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
5.2 DOM (Document Object Model). 2 Motto: To write it, it took three months; to conceive it three minutes; to collect the data in it — all my life. —F.
Extending HTML CPSC 120 Principles of Computer Science April 9, 2012.
DHTML - Introduction Chapter Introduction to DHTML, the DOM, JS review.
Internet & World Wide Web How to Program, 5/e. © by Pearson Education, Inc. All Rights Reserved.
1 JavaScript Functions and Objects. 2 Objectives You will be able to Use JavaScript functions in JavaScript scripts. Get JavaScript functions executed.
1 Dr Alexiei Dingli XML Technologies SAX and DOM.
Internet & World Wide Web How to Program, 5/e. © by Pearson Education, Inc. All Rights Reserved.2 Revised by Dr. T. Tran for CSI3140.
1 Javascript DOM Peter Atkinson. 2 Objectives Understand the nature and structure of the DOM Add and remove content from the page Access and change element.
 2008 Pearson Education, Inc. All rights reserved Document Object Model (DOM): Objects and Collections.
Review of the DOM Node properties and methods Some ways of accessing nodes Appending, copying and removing nodes Event handling – Inline – Scripting –
Document Object Model. Back to the DOM… Javascript and the DOM  Originally, the Document Object Model (DOM) and Javascript were tightly bound  Each.
1 The Information School of the University of Washington Nov 1fit dom © 2006 University of Washington Document Object Model (DOM)
Rich Internet Applications 3. Client JavaScript. Document Object Model (DOM) The DOM, is an interface that allows scripts or programs to access and manipulate.
DOM (Document Object Model) - Parsing and Reading HTML and XML -
School of Computing and Information Systems CS 371 Web Application Programming JavaScript - DOM Modifying the Page from within.
Advanced DOM Builds on last presentation on DOM Allows you to dynamically create elements and position them on a page DOM methods/properties are W3C standard.
Understanding JavaScript and Coding Essentials Lesson 8.
11 Getting Started with ASP.NET Beginning ASP.NET in C# and VB Chapters 1 and 2.
Dr. Ahmet Cengizhan Dirican BIL 374 Internet Technologies 6. Dynamic Documents With JavaScript.
JS: Document Object Model (DOM) DOM stands for Document Object Model, and allows programmers generic access to: DOM stands for Document Object Model, and.
Introduction to JavaScript LIS390W1A Web Technologies and Techniques 24 Oct M. Cameron Jones.
Chapter 10 Dynamic HTML (DHTML) JavaScript, Third Edition.
XML DOM Week 11 Web site:
Internet & World Wide Web How to Program, 5/e.  JavaScript events  allow scripts to respond to user interactions and modify the page accordingly  Events.
1 Using jQuery JavaScript & jQuery the missing manual (Second Edition)
Chapter 6 © 2003 by Addison-Wesley, Inc Introduction - Dynamic HTML is not a new markup language - A dynamic HTML document is one whose tag attributes,
XP Tutorial 10 New Perspectives on JavaScript, Comprehensive 1 Working with Dynamic Content and Styles Creating a Dynamic Table of Contents.
111 State Management Beginning ASP.NET in C# and VB Chapter 4 Pages
COM621: Advanced Interactive Web Development Lecture 6 – JavaScript (cont.)
1 The Document Object Model. 2 Objectives You will be able to: Describe the structure of the W3C Document Object Model, or DOM. Use JavaScript to access.
THE DOM.
DHTML.
Applied Online Programming
CS 371 Web Application Programming
Web Development & Design Foundations with HTML5 7th Edition
Document Object Model (DOM): Objects and Collections
Revision.
Week 11 Web site: XML DOM Week 11 Web site:
CHAPTER 7 JavaScripts & HTML Documents
Introduction to Programming the WWW I
Working with Dynamic Content and Styles
Introduction to DHTML, the DOM, JS review
Chengyu Sun California State University, Los Angeles
Presentation transcript:

1 The Document Object Model SAMS Teach Yourself JavaScript in 24 Hours (Fourth Edition) Michael Moncur SAMS Publishing 2007

2 Objectives You will be able to: Describe the structure of the W3C Document Object Model, or DOM. Use JavaScript to access DOM objects. Dynamically modify page content with JavaScript using the DOM API.

3 The DOM Modern browsers hold everything that you see on a page in an elaborate data structure. The Document Object Model Similar to the XML Document Object Model You can access the contents from a JavaScript script. Add new content. Modify and delete content sent by the server.

4 The DOM The DOM consists of a hierarchy of JavaScript objects corresponding to the HTML tags that were sent to the browser by the server. Tree structure. "window" object is the root. Everything else is contained in an object included, at some level, in the window. Parent-child relationship. Reflects the containment relationships in the HTML. We can access any object from its parent.

5 The DOM API The objects that make up the DOM have public methods and properties. Define an API that scripts can use to interact with the user and modify page content.

6 The window Object When a script is running on a browser, there is always a current window object. The window contains a document object. The document object contains everything we see on the page. window.document refers to the document object of the current window. A global name, always available.

7 The window Object We can refer to the methods and properties of the current window directly without saying "window." Examples: alert('Hello!'); means window.alert('Hello!'); document.write('xxx'); means window.document.write('xxx');

8 Some Properties of window.document document.URL document.title document.referrer document.lastModified document.bgColor document.fgColor

9 Example: Accessing the DOM In Visual Studio, create a new Empty Web Site. DOM_Demo

10 Add HTML Page

11 Add test.html

12 Accessing a document Property

13 Accessing a document Property

14 Accessing Other document Properties Let's add some more content. This document was last modified on: document.write(document.lastModified + " "); document.write("Its title is " + document.title + " "); document.write("And its URL is " + document.URL + " ");

15 Accessing Other document Properties

16 document.write document.write only works correctly as the page is being loaded The script is executed as the browser loads the page. The function argument appears at that point in the rendered page.

17 Examine the DOM Add an HTML page to the website. simple.html Delete the and the xmlns. Keeping the page as simple as possible. Add a heading and a paragraph as shown on the next slide.

18 A Simple HTML Page

19 DOM Representation Each box in the diagram represents a DOM node. The boxes above the bottom row correspond to elements. The boxes in the bottom row are text nodes (not elements).

20 Terminology: Elements vs Nodes An element in the DOM corresponds to a start-tag end-tag pair and everything contained within them. Elements can contain other, smaller, elements in a parent-child relationship. Every element is a node in the DOM tree structure, but there are other kinds of nodes as well.

21 Nodes Nodes are the most basic objects in the DOM. The DOM consists of a tree of nodes. Kinds of nodes: Elements Defined by begin-end tag pairs Example:... Attributes Defined inside begin tags Example: Text Nodes Just text Example: This is a heading

22 Elements vs. Nodes Only elements can have children. Attribute nodes and text nodes are always children of element nodes. Cannot have child nodes of their own. No other node can be included in an attribute node or a text node.

23 Nodes JavaScript code can navigate the DOM by following links to child nodes, parent nodes, and sibling nodes. Script can add, modify, and delete nodes. Easier way: assign unique IDs to nodes that we want to act on. Script can then access the node by its ID.

24 Enable Script Debugging We will use the Visual Studio JavaScript Debugger to examine the DOM. Requires IE as browser Enable script debugging in your browser. Tools > Internet Options Advanced tab Browsing Uncheck “Disable Script Debugging (Internet Explorer)”

25 Enable Script Debugging

26 hello.js Add a JScript file, hello.js Permit us to use the Visual Studio debugger to examine the DOM. function say_hello() { alert('Hello'); doc = window.document; }

27 Add the Script to the HTML Page A Simple HTML Document <script language="Javascript" type="text/javascript" src="hello.js"> This is a heading. This is a paragraph.

28 Set a Breakpoint Try it!

29 Breakpoint Hit Right click on doc and select Quickwatch

30 Explore the Document End of Section

31 Manipulating Page Content with JavaScript Now let's look at how we can manipulate the page content with JavaScript using the DOM API. Let the user move an object around on the screen by clicking buttons. Hide an object and make it reappear Modify text Change text to an image. Drag and drop.

32 Positioning Content with JavaScript Teach Yourself JavaScript in 24 Hours (Fourth Edition), pages 213 – 216

33 Positioning with JavaScript Create a new empty web site. DOM_Positioning Download to website folder and add to website: Water_Lilies.jpg animate.js positioning.html Set positioning.html as start page. Downloads/DOM_Positioning/ Downloads/DOM_Positioning/

34 Website DOM Positioning

35 positioning.html Positioning Elements with JavaScript <script language="javascript" type="text/javascript" src="animate.js"> #square { position:absolute; top: 200; left: 100; width: 200; height: 200; border: 2px solid black; padding: 10px; background-color: #E0E0E0; } Style for element with specified ID

positioning.html Positioning Elements <input type="button" name="left" value="<- Left" onclick="pos(-1,0);" /> " onclick="pos(1,0);" /> <input type="button" name="up" value="Up" onclick="pos(0,-1);" /> <input type="button" name="down" value="Down" onclick="pos(0,1);" /> <input type="button" name="hide" value="Hide" onclick="hideSquare();" /> <input type="button" name="show" value="Show" onclick="showSquare();" /> This square is an absolutely positioned layer that you can move using the buttons above.

animate.js var x=100,y=200; function pos(dx, dy) { var sq; if (!document.getElementById) return; x += 10*dx; y += 10*dy; sq = document.getElementById("square"); sq.style.top = y; sq.style.left = x; } function hideSquare() { var sq; if (!document.getElementById) return; sq = document.getElementById("square"); sq.style.display = "none"; } function showSquare() { var sq; if (!document.getElementById) return; sq = document.getElementById("square"); sq.style.display="block"; }

38 Try it!

39 Set a Breakpoint Use QuickWatch to examine element “square”

40 The Square in the DOM Scroll down to id.

41 The Square in the DOM Scroll down and expand Style

42 The Square in the DOM Scroll down.

43 The Square in the DOM One of the values that we set in animate.js. Single step to end of function pos and then examine top again.

44 sq.style.top

45 The DOM API Node Properties nodeName Not the same as ID. Contents of -- p, body, etc. tagName in QuickWatch nodeType 1 for normal nodes 3 for text nodes 9 for the document node nodeValue – Text nodes only The text contained in the node

46 Node Properties innerHTML The HTML inside the node. Can be set as well as retrieved. innerText innerHTML without the HTML markup outerHTML The HTML that defines the node

47 innerHTML

48 outerHTML

49 Node Relationship Properties firstChild lastChild childNodes (Array) previousSibling nextSibling Can be viewed in QuickWatch JavaScript code can use these properties to navigate in the DOM.

50 sq.firstChild

51 More DOM API Document Methods getElementById (id ) getElementsByTagName (tag ) createTextNode (text ) createElement ( tag )

52 Node Methods appendChild(new ) InsertBefore (new, old ) replaceChild (new, old ) removeChild (node ) hasChildNodes() cloneNode(); JavaScript code can use these methods to examine and modify the DOM.

53 Example: Modify Existing Text Add a button to DOM_Positioning When button is clicked, the script will modify the text shown inside the box.

54 Modify Existing Text Add to animate.js: function modifySquareText() { if (!document.getElementById) return; var sq = document.getElementById("square"); sq.firstChild.nodeValue = "New text inside the box"; }

55 Add Button to positioning.html... <input type="button" name="show" value="Show" onClick="showSquare();" /> <input type="button" name="modify" value="Modify" onclick="modifySquareText();" /> Build and run.

56 positioning.html with New Modify Button

57 After Modify is Clicked Note that the original buttons still work normally.

58 Replacing a Node Let’s modify the Modify button’s function to replace the text node in “square” with an image. function modifySquareText() { if (!document.getElementById) return; var sq = document.getElementById("square"); var img = document.createElement(' '); sq.replaceChild(img, sq.firstChild); } Comment out the original version.

59 After Modify is Clicked

60 Adding Text to a Page Let’s let the user add new text to the movable square. Add an input box to the form. When the user clicks “Modify” create a new text node containing the user’s input and add it to the square.

61 The New Input Box In positioning.html, just before the end of the form, add:

62 positioning.html with New Input Box

63 Modify Function modifySquareText() function modifySquareText() { if (!document.getElementById) return; var new_text = document.form1.input_box.value; var new_node = document.createTextNode (" " + new_text); var sq = document.getElementById("square"); sq.appendChild(new_node); document.form1.input_box.value=""; } Comment out previous version.

64 New Version of positioning.html User input

65 After Modify Clicked

66 The Square is Still Movable

67 Changing the Page Heading While we are at it, let’s let the modify button modify the heading as well. The title “Positioning Elements” is the only tag on the page. Use this as an opportunity to demonstrate getElementsByTagName

68 Function updateHeading() function updateHeading() { if (!document.getElementsByTagName) return; var headings = document.getElementsByTagName("h1"); var pageHeading = headings[0]; pageHeading.firstChild.nodeValue = "Square text has been modified"; } Add call to updateHeading at the end of function modifySquareText().

69 New Version of positioning.html

70 New Version of positioning.html End of Section

71 Let the User Drag and Drop the Square We can handle MouseDown, MouseMove, and MouseUp events in order to implement drag and drop in JavaScript. Note: This is a simple example. In a real app we would do something in response to the drag and drop rather than just moving the object on the screen.

72 Drag and Drop Add a new JScript file to the website: drag_and_drop.js New tag in positioning.html head: <script language="javascript" type="text/javascript" src="drag_and_drop.js">

73 Browser Differences Different browsers use different properties for the cursor position on MouseMove: pageX, pageY clientX, clientY Try one. If it doesn't exist, try the other.

74 Drag and Drop in Progress Apps typically provide feedback to the user indicating that a drag and drop operation is in progress. Let's make the border red while the square is being dragged.

75 drag_and_drop.js var dx, dy; // Set up when the page loads window.onload = Setup; function Setup() { if (!document.getElementById) return; var sq = document.getElementById("square"); // Set event handler sq.onmousedown = Start_Drag; } Note alternative to Avoid cluttering the HTML!

function Start_Drag(e) { var mouse_x, mouse_y; if (!e) var e = window.event; // Accomodate different browsers if (e.pageX) { mouse_x = e.pageX; mouse_y = e.pageY; } else if (e.clientX) { mouse_x = e.clientX; mouse_y = e.clientY; } else return; // No browser support var sq = document.getElementById("square"); sq.style.borderColor = "Red"; // Calculate distances from mouse position to square. dx = mouse_x - sq.offsetLeft; dy = mouse_y - sq.offsetTop; // Set event handlers sq.onmousemove = Move; sq.onmouseup = Drop; sq.onmousedown = null; }

function Move(e) { var mouse_x, mouse_y; // Track mouse movements if (!e) var e = window.event; if (e.pageX) { mouse_x = e.pageX; mouse_y = e.pageY; } else if (e.clientX) { mouse_x = e.clientX; mouse_y = e.clientY; } else return; // Update position of the square x = mouse_x - dx; y = mouse_y - dy; var sq = document.getElementById("square"); sq.style.left = x; sq.style.top = y; }

function Drop() { var sq = document.getElementById("square"); sq.style.borderColor = "black"; // Update event handlers sq.onmousemove = null; sq.onmouseup = null; sq.onmousedown = Start_Drag; } Try it!

79 Mouse Down

80 Drag

81 Mouse Up

82 Other Browsers Chrome

83 Other Browsers Firefox

84 Assignment Try these examples for yourself. Experiment with different browsers.

85 References Official documentation on the DOM can be found on the W3C website: Exhaustive, but difficult to understand and use. Some more accessible resource: w3schools javaScript and HTML DOM Reference Mozilla DeveloperNetwork Gecko DOM Reference quirksmode DOM Tutorial