JAVASCRIPT Document Object Model DOM Browser Object Model

  • Slides: 42
Download presentation
JAVASCRIPT Document Object Model (DOM) Browser Object Model (BOM)

JAVASCRIPT Document Object Model (DOM) Browser Object Model (BOM)

Document Object Model (DOM) Paraphrased from Wikipedia: That which we see as a window

Document Object Model (DOM) Paraphrased from Wikipedia: That which we see as a window displaying a document, the browser program sees as a hierarchical collection of objects. When the browser parses a document, it creates a collection of objects that define the document and detail how it should be displayed. The object the browser creates is known as the document object. The top level of the hierarchy is the window object, which contains the information not only about the document object, but also about the window displaying the document. The DOM applies not only to web browsers, but also to other types of documents you may have heard of such as XML and XHTML. When applied to web browsers, the DOM is sometimes referred to as the browser object model, or BOM.

DOM vs BOM Browser Object Model (BOM) – A term sometimes applied to the

DOM vs BOM Browser Object Model (BOM) – A term sometimes applied to the DOM specifically referring to the browser context. ‘BOM’ is not an “official” standard. In addition, the BOM is notorious for being interpreted differently by different browsers. This has always been a major problem in web development, and is one area rife with cross-browser compatibility issues. However, because we will be discussing the DOM only within the context of using a web browser, you may encounter the use of BOM as well as DOM.

DOM The DOM (or BOM) is a set of several common web objects inherited

DOM The DOM (or BOM) is a set of several common web objects inherited from the browser "context" that are accessible to Java. Script We have already seen a couple of these objects: window document

DOM Hierarchy For the time being, you can think of the above objects as

DOM Hierarchy For the time being, you can think of the above objects as special types of variables. These special variables are more accurately called 'objects'. Think of these as variables that have been pre-declared for you. In most cases, these variables already have values. As with variables, we can view and / or modify their values.

Inside a ‘window’ object Every box in this illustration is called a ‘node’. <html>

Inside a ‘window’ object Every box in this illustration is called a ‘node’. <html> <head> <title>DOM Example</title> </head> <body> <div id="main_content"> <p>A paragraph of content with <i>some text in italics. </i></p> <p>A second paragraph of content. This paragraph also has an image of a <img src="baseball. jpg"> baseball embedded. </p> </div> </body> </html> In j. Query we would select all paragraphs on the page with: $('p') In plain Java. Script we would use: window. document. p

window Object By 'window' we are referring to the part of the browser that

window Object By 'window' we are referring to the part of the browser that surrounds the HTML document You can use this window object to open new windows (or tabs), close existing windows (or tabs), resize windows, change the status of windows, dealing with frames, working with timers, etc This object is also your handle to access the lower level items in the hierarchy (see previous slide). The window object incudes methods such as alert() and write() (via the 'document' object) that you have seen previously. The window object is implicit: In theory, we should need to write: window. alert() or window. document. write() However, because it is a global object (beyond the scope of this discussion), the ‘window’ reference is implicitly understood and, therefore, typing out window turns out to be optional.

Example: Accessing your images via the DOM window. document. images In j. Query: $('img')

Example: Accessing your images via the DOM window. document. images In j. Query: $('img')

Accessing Elements by 'id' <img src=“firetruck. jpg” id=“truck_pic” id=“firetruck” alt=“pic of truck”> <img src=“baseball.

Accessing Elements by 'id' <img src=“firetruck. jpg” id=“truck_pic” id=“firetruck” alt=“pic of truck”> <img src=“baseball. jpg” id=“ball_pic” name=“baseball” alt=“pic of baseball”> An element can be accessed by its 'id' attribute (if it has one): alert( document. get. Element. By. Id('firetruck'). alt ); //Outputs: ‘pic of truck’

Accessing Elements by 'name' <img src=“firetruck. jpg” id=“truck_pic” id=“firetruck” alt=“pic of truck”> <img src=“baseball.

Accessing Elements by 'name' <img src=“firetruck. jpg” id=“truck_pic” id=“firetruck” alt=“pic of truck”> <img src=“baseball. jpg” id=“ball_pic” name=“baseball” alt=“pic of baseball”> An element can be accessed by its 'name' attribute (if it has one): alert( document. images. firetruck. alt ); //Outputs: ‘pic of truck’ Note that in this case we retrieve all images, and then use the name attribute to indicate which particular image we want to access.

Accessing Elements by array <img src=“firetruck. jpg” id=“truck_pic” id=“firetruck” alt=“pic of truck”> <img src=“baseball.

Accessing Elements by array <img src=“firetruck. jpg” id=“truck_pic” id=“firetruck” alt=“pic of truck”> <img src=“baseball. jpg” id=“ball_pic” name=“baseball” alt=“pic of baseball”> You can access an element using array notation: alert( document. images[0]. alt ); //Outputs 'pic of truck' alert( document. images[1]. alt ); //Outputs 'pic of ball' That is, document. images selects all images in the document. This is analogous to j. Query's: $('img') Array notation is simply a way to refer to the items in the numerical order in which they appear. Note that array notation begins at 0.

Who cares? Are you impressed yet? Okay, I agree that having all of these

Who cares? Are you impressed yet? Okay, I agree that having all of these different ways of accessing things may not seem useful. In addition, the fact that j. Query seems to make it all so much easier. Patience, grasshopper: Over time in your web-development lives, you will see that there are situations where the DOM is preferable – even necessary. In addition, there will be times when you will find that the particular techniques of accessing elements each have their strengths.

dom_example. htm <html> <head> <title>DOM Example</title> <script type="text/javascript"> function dom. Test(){ var images =

dom_example. htm <html> <head> <title>DOM Example</title> <script type="text/javascript"> function dom. Test(){ var images = document. images; //Recall that 'window' is implicit var str="List of Alt Values: n"; for (var i=0; i<images. length; i++) { //this is called a 'loop' str += images[i]. alt + "n"; } alert(str); } //end dom. Test() </script> </head> <body onload="dom. Test()"> <p>Some smiley-face balls: </p> <img src="blue_ball. jpg" alt="Pic of blue ball" height="80" width="80"> <img src="green_ball. jpg" alt="Pic of green ball" height="80" width="80"> <img src="red_ball. jpg" alt="Pic of red ball" height="80" width="80"> </body> </html>

Examples using pop-up windows window. alert() alert(“This is a message”); window. confirm() § Returns

Examples using pop-up windows window. alert() alert(“This is a message”); window. confirm() § Returns a boolean: § § § True – if user clicks ‘OK’ False – if user clicks ‘Cancel’ Example: var result = confirm(“Continue ? ”); window. prompt() Returns the String entered by the user, if the user clicks ‘OK’ Returns ‘null’ if the user clicks ‘Cancel’ var response = prompt(“Your Name ? ”, [default] ); Don't forget that even though these methods are part of the 'window' object, the reference to 'window' is "implicit" (i. e. it's presence is assumed). Therefore for clarity, we typically just leave it out.

Opening a new browser window To open a window (or tab) use: window. open(arg

Opening a new browser window To open a window (or tab) use: window. open(arg 1, arg 2, arg 3); All 3 arguments are optional, All 3 take Strings as their data types arg 1 - the URL of the document arg 2 - window name (for purposes of referencing if needed) – Note: This is not the <title> of the window arg 3 - window options to control the appearance of the window. This is where you indicate all desired options (in one single string, separated by commas). Not all options are always available. The options available to you depend on the context. Example: window. open("http: //google. com", "height=600, width=400, toolbar=no");

window. open("http: //google. com", "goog. Win", "height=600, width=400, toolbar=no"); window. open("http: //google. com", "goog.

window. open("http: //google. com", "goog. Win", "height=600, width=400, toolbar=no"); window. open("http: //google. com", "goog. Win", "height=600, width=400, toolbar=yes");

window. open() - options

window. open() - options

window. open() - options

window. open() - options

Opening a new browser window var new. Window = window. open("", "win. Info", "height=200,

Opening a new browser window var new. Window = window. open("", "win. Info", "height=200, width=400"); new. Window. document. write('The current date is: ' + Date() + ' '); new. Window. document. write('<input type="button" value="Greet Me" onclick="alert('hi')">'); • • • Note how this time, we need to include the reference to the current window object, 'new. Window' in order to ensure that our code applies to the appropriate window Note the advantage of keeping single and double quotes separate Note the need to use escape characters in the 'onclick' attribute

Java. Script API This is a good time to ask ourselves where to find

Java. Script API This is a good time to ask ourselves where to find the Java. Script API. There are several resources on the web that provide this information. One we will check out here is provided by the folks at Mozilla: https: //developer. mozilla. org/en-US/docs/Web/Java. Script

window. open() API from W 3 Schools http: //www. w 3 schools. com/jsref/met_win_open. asp

window. open() API from W 3 Schools http: //www. w 3 schools. com/jsref/met_win_open. asp Note the need for a 'Browser Support' section.

DOM Hierarchy

DOM Hierarchy

frames Object The frames object has the following properties: parent length name The parent

frames Object The frames object has the following properties: parent length name The parent (frameset) can access the children frames by their names. The children can access the other child by going through the parent. Frames are no longer popular – in fact, their use has fallen out of favor and rarely recommended. They are discussed here simply for completeness and because it is possible you will encounter them in legacy code.

DOM Hierarchy

DOM Hierarchy

location Object alert( window. location. href ); //outputs the current URL Recall: alert( location.

location Object alert( window. location. href ); //outputs the current URL Recall: alert( location. href ) would also work…

location Object A URL such as: http: //learning. javascript. info/ch 09 -01. htm? a=1

location Object A URL such as: http: //learning. javascript. info/ch 09 -01. htm? a=1 Can be broken down into the following property values of the 'location' object: host/hostname: learningjavascript. info protocol: http: search: ? a=1 href: http: //learning. javascript. info/ch 09 -01. htm? a=1 e. g. alert( window. location. protocol ); //outputs ‘http: ’

Timing Events It is possible to time events using Java. Script. There are two

Timing Events It is possible to time events using Java. Script. There are two functions in particular that can be useful: set. Timeout() and set. Interval() will execute a function that you name over and over again at specified intervals (e. g. every 3 seconds). Of course, you will then need a way to stop the execution. This is not difficult, but requires some extra code that we will not get into just now. set. Timeout() will execute a function once, after a certain time interval has passed. Both of these methods are part of the ‘window’ object, in exactly the same way that alert() is a method of the window object.

//Example: set_timeout_example. htm <html> <head> <title>set. Timeout() Example</title> <script type="text/javascript"> function go() { alert('Ready?

//Example: set_timeout_example. htm <html> <head> <title>set. Timeout() Example</title> <script type="text/javascript"> function go() { alert('Ready? Click the okay button, then wait 2 seconds to be greeted. '); //After the user closes the alert box above, we wait 2 seconds //and then the greet. User() function is invoked set. Timeout("greet. User()", 2000); } function greet. User() { alert('Hello!!!'); } </script> </head> <body onload="go()"> </body> </html>

DOM Hierarchy

DOM Hierarchy

navigator Object Allows you to find out information about the client (e. g. web

navigator Object Allows you to find out information about the client (e. g. web browser or other agent) that is accessing your page. Items you can check for / about include: The type of browser and related information ('user. Agent') The version number ('app. Version') Whether cookies are enabled ('cookie. Enabled') The OS on which the client is running ('platform') Which plug-ins are installed ('plugins') This is a common technique by which your smartphone is redirected to a 'small-screen friendly' version of a web page

'navigator' object properties Property Description app. Codename of the browser code base app. Name

'navigator' object properties Property Description app. Codename of the browser code base app. Name name of the browser code base app. Minor. Version browser minor version app. Version browser major version platform that browser is on plugins array of plugins supported user. Agent full agent description for browser user. Language language supported by browser Example: history_navigator_properties. htm

history_navigator_properties. htm as run on a Windows desktop computer

history_navigator_properties. htm as run on a Windows desktop computer

history_navigator_properties. htm as run on an i. Phone

history_navigator_properties. htm as run on an i. Phone

DOM Hierarchy

DOM Hierarchy

document Object We have now gone through several of the properties of the window

document Object We have now gone through several of the properties of the window object, albeit somewhat briefly. We will now return to one object with which we are already somewhat familiar, the document object. Of all the objects encapsulated by the window object, the document object is one JS programmers interact with frequently. The document object provides access to any element on the page, either individually or as a collection (e. g. a specific image, or an array of all of the images). We've already seen a few properties/methods: get. Element. By. Id, get. Element. By. Tag. Name and writeln. Other things we can access/do via the document object: Get the links on a page. Alter images on the page Change html contained within a page element

inner. HTML Property This property of the document object allows you to directly view

inner. HTML Property This property of the document object allows you to directly view and modify the HTML present inside the document. Though deprecated, this property is still available to HTML-5 and is present in a lot of legacy code. However, there are better ways of modifying HTML content (e. g. via node access, via j. Query's html() function, and others). <script> function go() { alert("Check out the text, then click the okay button"); document. get. Element. By. Id('click'). inner. HTML = "<h 1>Some H 1 Text</h 1>"; } </script> <div id="click" onclick="go()"> <h 2>Click Me</h 2> </div>

document Object example Here is a code example in which we access the 'links'

document Object example Here is a code example in which we access the 'links' property of the document object. This property retrieves all of the anchor <a> tags as a collection. We will then extract all of the URLs from those <a> elements and output them as an ordered list: var links = ""; for (var i = 0; i < document. links. length; i++) { links = links + "<li>" + document. links[i]. href + "</li>"; } document. write("<ol>"); document. write(links); document. write("</ol>"); Examples: document_object_links. htm

Nodes The W 3 C’s specification for the DOM works by describing a web

Nodes The W 3 C’s specification for the DOM works by describing a web document as a series of “nodes”. A web page’s DOM is essentially, a ‘tree’ in which there are parents, children, siblings, and so on. The easiest way to see how all of this plays out is probably by example. We will first open up a document to view the HTML. We will then use a ‘DOM Inspector’ to see the visual representation of the DOM as a collection of nodes. Most browsers have some form of DOM Inspector built in, or available via plug-ins.

<html> Nodes <head> <title>Page as Tree</title> </head> <body> <div id="div 1"> <!-- paragraph one

<html> Nodes <head> <title>Page as Tree</title> </head> <body> <div id="div 1"> <!-- paragraph one --> <p>To better understand the document tree, consider a web page that has a head and body section, a page title, and the body contains a div element that itself contains a header and two paragraphs. One of the paragraphs contains <i>italicized text</i>; the other has an image. </p> <!-- paragraph two --> <p>Second paragraph with image. <img src="washington. jpg" alt="Painting of Washington"/></p> </div> </body> </html>

Firefox's DOM Inspector

Firefox's DOM Inspector

Node Properties inherited from 'Node' Every Node object has a series of properties and

Node Properties inherited from 'Node' Every Node object has a series of properties and methods courtesy of a DOM object called 'Node'. These include: node. Name, node. Value, node. Type parent. Nodes, child. Nodes first. Child, last. Child previous. Sibling, next. Sibling attributes owner. Document namespace. URI prefix local. Name Example: node_object_properties. htm

Node Properties inherited from Element' We have just looked at some properties available to

Node Properties inherited from Element' We have just looked at some properties available to nodes courtesy of the object 'Node'. Every node has an additional series of properties and methods courtesy of another DOM object called 'Element'. These include: get. Attribute(name); set. Attribute(name, value); remove. Attribute(name); get. Attribute. Node(name); set. Attribute. Node(attr); remove. Attribute. Node(attr); has. Attribute(name); Example: node_element_properties. htm