420 likes | 430 Views
Explore the fundamental concepts and hierarchy of DOM and BOM in JavaScript for efficient web development. Learn to access, manipulate, and interact with objects using window and document. Grasp the differences between DOM and BOM, and their significance in cross-browser compatibility.
E N D
JAVASCRIPT Document Object Model (DOM) Browser Object Model (BOM)
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. Document Object Model (DOM)
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 from the browser "context" that are accessible to JavaScript • 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 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> <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 jQuery we would select all paragraphs on the page with: $('p') In plain JavaScript we would use: window.document.p
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 jQuery: $('img')
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.getElementById('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.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.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 jQuery'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 different ways of accessing things may not seem useful. In addition, the fact that jQuery 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 domTest(){ 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 domTest() </script> </head> <body onload="domTest()"> <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 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(arg1, arg2, arg3); • All 3 arguments are optional, All 3 take Strings as their data types • arg1 - the URL of the document • arg2 - window name (for purposes of referencing if needed) – Note: This is not the <title> of the window • arg3 - 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", "googWin", "height=600, width=400, toolbar=no"); window.open("http://google.com", "googWin", "height=600, width=400, toolbar=yes");
Opening a new browser window var newWindow = window.open("", "winInfo", "height=200, width=400"); newWindow.document.write('The current date is: ' + Date() + '<br>'); newWindow.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, 'newWindow' 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
JavaScript API • This is a good time to ask ourselves where to find the JavaScript 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/JavaScript
window.open() API from W3 Schools http://www.w3schools.com/jsref/met_win_open.asp Note the need for a 'Browser Support' section.
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.
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/ch09-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/ch09-01.htm?a=1 e.g. alert( window.location.protocol ); //outputs ‘http:’
Timing Events It is possible to time events using JavaScript. There are two functions in particular that can be useful: setTimeout() and setInterval(). setInterval() 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. setTimeout() 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>setTimeout() 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 greetUser() function is invoked setTimeout("greetUser()",2000); } function greetUser() { alert('Hello!!!'); } </script> </head> <body onload="go()"> </body> </html>
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 ('userAgent') • The version number ('appVersion') • Whether cookies are enabled ('cookieEnabled') • 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 Example: history_navigator_properties.htm
history_navigator_properties.htm as run on a Windows desktop computer
history_navigator_properties.htm as run on an iPhone
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: getElementById, getElementByTagName 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
innerHTML 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 jQuery's html() function, and others). <script> function go() { alert("Check out the text, then click the okay button"); document.getElementById('click').innerHTML = "<h1>Some H1 Text</h1>"; } </script> <div id="click" onclick="go()"> <h2>Click Me</h2> </div>
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 W3C’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.
Nodes <html> <head> <title>Page as Tree</title> </head> <body> <div id="div1"> <!-- 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. <br> <img src="washington.jpg" alt="Painting of Washington"/></p> </div> </body> </html>
Node Properties inherited from 'Node' Every Node object has a series of properties and methods courtesy of a DOM object called 'Node'. These include: • nodeName, nodeValue, nodeType • parentNodes, childNodes • firstChild, lastChild • previousSibling, nextSibling • attributes • ownerDocument • namespaceURI • prefix • localName • Example: node_object_properties.htm
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: • getAttribute(name); • setAttribute(name, value); • removeAttribute(name); • getAttributeNode(name); • setAttributeNode(attr); • removeAttributeNode(attr); • hasAttribute(name); Example: node_element_properties.htm