Transcript Document Object Model
Document Object Model
Back to the DOM…
Javascript and the DOM
Originally, the Document Object Model (DOM) and Javascript were tightly bound Each major browser line (IE and Netscape) had their own overlapping DOM implementation There's also some jargon issues, eg. DHTML… Now, the DOM is a separate standard, and can be manipulated by other languages (eg Java, server side javascript, python, etc) Browsers still differ in what parts of the standard they support, but things are much better now
window * location * frames
Review: DOM Structure
* navigator * event Objects are in a hierarchy The window is the parent for a given web page Document is the child with the objects that are most commonly manipulated * screen * document o links o anchors o images o filters o forms o applets o embeds o plug-ins o frames o scripts o all o selection o stylesheets o body table from: http://www.webmonkey.com/webmonkey/97/32/index1a.html?tw=authoring
DOM Tree
The usual parent/child relationship between node Like any other tree, you can walk this diagram from http://www.w3schools.com/htmldom/default.asp
Referencing Objects
Objects can be referenced by their id or name (this is the easiest way, but you need to make sure a name is unique in the hierarchy) by their numerical position in the hierarchy, by walking the array that contains them by their relation to parent, child, or sibling (parentNode, previousSibling, nextSibling, firstChild, lastChild or the childNodes array
A div example
Zen Garden Example 1
A loop of code to list the links….
for (var i = 0; i < document.links.length; i++) { document.write("Link number " + i + " has these properties:
"); document.write("nodeName is " + document.links[i].nodeName + "
"); document.write("nodeType is " + document.links[i].nodeType + "
"); document.write("parentNode.nodeValue is " + document.links[i].parentNode.nodeValue + "
"); document.write("firstChild is " + document.links[i].firstChild + "
"); document.write("firstChild.nodeValue is " } + document.links[i].firstChild.nodeValue + "
"); document.write("href is " + document.links[i].href + "
");
Zen Garden Example 2
Same as example one, but with another loop to look for all span tags….
Zen Garden Example 2
I added a little javascript to the sample file from zen garden This will search for a given tag using the getElementsByTagName() method The result of this method is an array, and we can walk that array and then write out different properties and values for the elements found by getElementsByTagName() There's also a getElementsById() method
Zen Garden Example 2
var look_for="span"; document.write("
Looking for " + look_for + " tags
"); var x=document.getElementsByTagName(look_for); for (var i = 0; i < x.length; i++) { document.write("Tag " + look_for + " number " + i + " has these properties:"); document.write("nodeName is " + x[i].nodeName + "
"); document.write("nodeValue is " + x[i].nodeValue + "
"); document.write("nodeType is " + x[i].nodeType + "
"); document.write("id is " + x[i].id + "
"); document.write("name is " + x[i].name + "
"); document.write("parentNode is " + x[i].parentNode + "
"); document.write("parentNode.nodeValue is " + x[i].parentNode.nodeValue + "
"); document.write("firstChild is " + x[i].firstChild + "
"); document.write("firstChild.nodeValue is " + x[i].firstChild.nodeValue + "
"); }
Learning The DOM
The only way is to read and try things out Build a test document, with things you've learned Gecko_test.html is an example adapted from the mozilla site….
Gecko Test version 1
Notice the use of eval function setBodyAttr(attr,value) { // eval causes a string to be executed eval('document.body.' + attr + '="' + value + '"'); document.main_form.object_manipulated.value='document.body.' + attr + '="' + value + '"'; } gecko_test01.html
Gecko Test version 1
And a select gecko_test01.html
Gecko Test version 1
What's wrong with this? (hint: I'm violating a basic rule of coding…) gecko_test01.html
Gecko Test version 2
Setting a variable for the options in select (why backslashes at the EOLs?): var select_string='\ \ \ \ \ '; gecko_test02.html
Gecko Test version 2
And now, I can call that list with a write How could I further refine this?
gecko_test02.htmlManipulating Objects
As said, it's easiest to reference objects by id To do this easily, use getElementById(), which returns the element with the given id For example, if you want to find a div with the id of "my_cool_div", use getElementById("my_cool_div") Keep in mind that it's the element itself that's returned, not any particular property
Using divs
Div properties can be dynamically manipulated You can use this to make menus more dynamic
colors: The first version
The basic div:
colors01.html
colors: The First Version
And a function (notice the alert): colors01.html
In Action
colors01.html
What's wrong with this? What would be better?
Version 2
The div structure, sans link:
Version 2
And the function, with some vars colors02.html
Version2
Much cleaner div clickable means no issues with color of link, but sacrifices visited link color (how could that be fixed?) Use of variables for colors mean it's much easier to change them (but this could be made much easier with php in the background…)
innerHTML
innerHTML is a property of any document element that contains all of the html source and text within that element This is not a standard property, but widely supported--it's the old school way to manipulate web pages Much easier than building actual dom subtrees, so it's a good place to start Very important--innerHTML treats everything as a string, not as DOM objects (that's one reason it's not part of the DOM standard)
Using These….
You can reference any named element with getElementById() You can read from or write to that element with innerHTML For example: getElementById("mydiv").innerHTML
="new text string";
A Simple DOM example
This some simple html to display
Manipulating Visibility
You can manipulate the visibility of objects, this from http://en.wikipedia.org/wiki/DHTML The first part displays an element if it's hidden… function changeDisplayState (id) { … trigger=document.getElementById("showhide"); target_element=document.getElementById(id); if (target_element.style.display == 'none' { || target_element.style.display == "") target_element.style.display = 'block'; trigger.innerHTML = 'Hide example'; } 31_dhtml_example.html
Manipulating Visibility
And the second hides the same element if it's visible … else { target_element.style.display = 'none'; } trigger.innerHTML = 'Show example'; } 31_dhtml_example.html
Controlling the back end
And you can enable or disable functionality, for example, you can disable links dynamically… function killAll() { var stuff = document.getElementsByTagName("A"); for (var i=0; i 35_disable_links.html …and reenable them… function resurrectAll() { var stuff = document.getElementsByTagName("A"); for (var i=0; i 35_disable_links.html check out Nifty Corners Cube: http://www.html.it/articoli/niftycube/index.ht ml And zoom: http://valid.tjp.hu/zoom/index_en.html Ant Jesse James Garrett coined the term, Asynchronous Javascript And XML It's not a language or program, but rather an approach Standards-based presentation using XHTML and CSS Dynamic display and interaction using the Document Object Model Data interchange and manipulation using XML and XSLT Asynchronous data retrieval using XMLHttpRequest And JavaScript binding everything together An acronym A monolith or unified technology (it is rather an approach based on a number of disparate technologies) A standard (and it's not likely to become one, although it will influence standards, since it's really just an approach) A product (although you can buy a lot of it these days--but most of that are really frameworks) When you load a web page and then Use the XMLHttpRequest object to get some more data, and then Use Javascript to change some of the data on your web page (but not all of it, and not by reloading the page), then What you're doing is Ajax Ajax inserts a chunk of code in the browser that handles server queries for small chunks of data used to update a document diagram from http://www.adaptivepath.com/ideas/essays/archives/000385.php Javascript has no concept of I/O, nor can it access sockets But Netscape/Mozilla and MS both worked out an object in the browser that can submit data requests via the web In MS, this is done via ActiveX, via the Microsoft.XMLHTTP object In Gecko, it's the XMLHttpRequest() object, and that's what we'll play with Remember, Javascript and the DOM are OOP, so objects have properties, with values, and can receive messages, based on events, and send messages via methods In most of the examples so far, the user is the one that causes an event to occur--eg. the nav buttons in the slideshow call functions based on an event initiated by a carbon unit Other events don't require human interaction--these type of events are called "listeners"… You can create your own listeners if you need to An object that can load web resources from within javascript So you create an instance of this object Call the open method from that object with a url and a method to use (GET or POST) It makes the HTTP request, and as it does so, one of it's properties cycles through the states of the HTTP request You watch that, and when the request is complete, you can get the data that was retrieved abort() getAllResponseHeaders() getResponseHeader(header) open(method, url): method is POST, GET, or PUT) send(body): body is the content of a post…. setRequestHeader(header, value) onreadystatechange: sets a method to be called on any state change, eg. a listener readState: 0 Uninitated 1 Loading 2 Loaded 3 Interactive 4 Complete responseText: server response as a string responseXML: server response as xml status: as an HTTP code, eg 404 statusText: the accompanying text function makeRequest(url) { var http_request = false; if (window.XMLHttpRequest) { // Mozilla, Safari, ... http_request = new XMLHttpRequest(); if (http_request.overrideMimeType) { } http_request.overrideMimeType('text/xml'); } } if (!http_request) { alert('Giving up :( Cannot create an XMLHTTP instance'); return false; http_request.onreadystatechange = function() { alertContents(http_request); } http_request.open('GET', url, true); http_request.send(null); } 00_ajax_demo.html: i function alertContents(http_request) { } if (http_request.readyState == 4) { if (http_request.status == 200) { } alert(http_request.responseText); } else { alert('There was a problem with the request.'); } 00_ajax_demo.html: i At first, this kind of call wasn't restricted But that meant that if one could inject javascript into a web page, eg. via a comment form, one could pull live data into a users brower, and thus escape the sandbox So now, this method is generally restricted to the same named server… 00_ajax_demo.html: in this one, I'm just pulling some data from the server, and stuffing the results into an alert After Garret's coining of the term ajax, several people independently presented similar systems--this is to be expected, since XMLHttpRequest has been around a while Most of these used the same basic approach to pull html or other data types than xml, or didn't use the dom specification Jah is the work of Kevin Marks Jah relies on two simple functions, one to open the request, and the other to change the data Instead of manipulating the dom directly, jah uses the innerHTML property to manipulate the page See: http://homepage.mac.com/kevinmarks/staticjah.html for an example (or the copy I've got in the lessons folder) function jah(url,target) { } } // native XMLHttpRequest object document.getElementById(target).innerHTML = 'sending...'; if (window.XMLHttpRequest) { req = new XMLHttpRequest(); req.onreadystatechange = function() {jahDone(target);}; req.open("GET", url, true); req.send(null); // IE/Windows ActiveX version } else if (window.ActiveXObject) { req = new ActiveXObject("Microsoft.XMLHTTP"); if (req) { req.onreadystatechange = function() {jahDone(target);}; req.open("GET", url, true); req.send(); } } function jahDone(target) { // only if req is "loaded" if (req.readyState == 4) { // only if "OK" if (req.status == 200) { results = req.responseText; document.getElementById(target).innerHTML = results; } else { document.getElementById(target).innerHTML="jah error:\n" + req.statusText; } } Make live insertions into a page via the DOM We'll do more of this next weekControlling the back end
Getting fancier
What else can you do?
Getting Started with Ajax
Garrett's take on what Ajax is
What Ajax is not
Ok, but what IS Ajax?
Ajax Model
But remember…
Objects and Events
XMLHttpRequest Object
XMLHttpRequest Methods
XMLHttpRequest Properties
An Example…
Security Concerns
Some Examples
Jah and Ajah and Ahah: HA!
Jah
Jah Function
Jahdone Function
Jah in Action
So how can we use this?