javascript’s window object represents the browser …classes.pint.com/webpub4/lecture3/big.pdf–...

58
Web 4 http://www.pint.com/classes/web4 JavaScript’s Window object represents the browser window or potentially frame that a document is displayed in. Every window that is open on the screen can be referenced and manipulated by an instance of this object, though there may be security considerations for doing so particularly if the window is not one your script created. Be default we often assume the object name when we are writing scripts since the default “window” can be assumed to be the current window. For example, window.document.write(‘hi’); document.write(‘hi’); are equivalent.

Upload: truongkhuong

Post on 10-May-2018

218 views

Category:

Documents


1 download

TRANSCRIPT

Web 4http://www.pint.com/classes/web4

����������

• JavaScript’s Window object represents the browser window or potentially frame that a document is displayed in.

• Every window that is open on the screen can be referenced and manipulated by an instance of this object, though there may be security considerations for doing so particularly if the window is not one your script created.

• Be default we often assume the object name when we are writing scripts since the default “window” can be assumed to be the current window. For example,

window.document.write(‘hi’); document.write(‘hi’);

are equivalent.

Web 4http://www.pint.com/classes/web4

������������ ����

• Properties of a window object include things like size, amount of chrome, position etc.

• Methods of windows include open, close, move, scroll, etc.

• The window is the “top” object so all methods like document object references are made within a window. Generically we might use document.getElementById( )which is short for window.document.getElementById( ) but with other windows (or frames) we might prepend the reference with the name of the window such as mywindow.document.getElementById( )

Web 4http://www.pint.com/classes/web4

�� � �� ��������� �� �

• Alerts – window.alert(string)

• Confirm– window.confirm(string)– Returns Boolean value

• Prompt– window.prompt(questionstring,answerstring)– Returns a string value (may be empty)

Web 4http://www.pint.com/classes/web4

� � �� �� ��������

• window.open(url, name, features, replace) where– url is a URL that indicates the document to load into the window– name is the name for the window that is useful to reference it later

on using the target attribute of HTML links.– features is a comma delimited string which lists the features of the

window (see pages 390-393)– replace is an optional Boolean value (true or false) that indicates if

the URL specified should replace the window's contents or not. This would apply to a window that was already created.

– Examplesecondwindow = open("http://www.yahoo.com", "yahoo",

"height=300,width=200, scrollbars=yes");– Demos

Web 4http://www.pint.com/classes/web4

����� ����������

• You can use windowname.document.write( ) until you are done with the initial document

• You can use DOM or BOM methods like document.getElementById( ) and document.all[ ] within windows to access anything

• Windows can have names set (both by the window.open()method and directly) and can reference who opened them (window.opener) we can use this to communicate between windows

Web 4http://www.pint.com/classes/web4

� �������� ��������

• You can open, close, move, resize, and scroll windows that you have created

• Windows have standard events like– onload, onunload– onblur, onfocus– onresize– onerror

• Window events can be set via <body> like <body onload=“alert(‘hi’)”> or registered via a window object

function sayHi() {alert(‘hi’)}window.onload = sayHi;

Web 4http://www.pint.com/classes/web4

������� �� � � ��� �

• In JavaScript you can– Create true modal windows (IE)– Create full-screen windows (both)– Create off-screen and always-lowered windows

(both)– Create chromeless windows (IE)

• Most of these extensions beg serious issues with usability and should be used with caution

Web 4http://www.pint.com/classes/web4

� �� � � � ��� � � �� �

• All browsers support changes to the page colors (bgColor,fgColor) and link colors (aLinkColor, vLinkColor, and linkColor) via the document object– Demo

• Another common document property is lastModifieddocument.writeln("Document Last Modified:

"+document.lastModified);– Returns a Date object so you can use the various Date properties

and methods discussed in JS Ref Chapter 7– Read only for obvious reasons

• Location related props– document.location, document.URL, document.referrer– Question of the difference between this and window.location!

Web 4http://www.pint.com/classes/web4

� � � �� �� �� � � � ��� � � ���

• We should already be familiar with the common document methods like– document.write( )– document.writeln( )– document.open( )– document.close( )

• Writing to the document is really only allowed in this style before page load, we use DOM methods or DHTML objects otherwise

Web 4http://www.pint.com/classes/web4

� � ������ ��� �� � � � ��� ���� � ����C ollection N am e

D escr ip tion B row ser C om p atib ility

D O M S u p p o rt

an ch ors[ ] A co llection o f a ll ancho rs as defined by < a n am e= ”an ch orn am e”> … < /a > .

N etscape 2+ , In te rnet E x p lo rer 3+

D O M Level 1

ap p lets[ ] A ll the Java A pp lets in a page as defined by the < a p p let> tag .

N etscape 3+ , In te rnet E x p lo rer 4+

D O M Level 1

em b ed s[ ] A ll the < em b ed > tags in a page . N etscape 3+ , In te rnet E x p lo rer 4+

N o D O M S upport

fo rm s[ ] A ll fo rm s in a page as se t by th e < form > tag

N etscape 2+ , In te rnet E x p lo rer 3+

D O M Level 1

im ages[ ] A co llection o f a ll im ages in the page ind icated by the H T M L < im g > tag

N etscape 3+ and In te rnet E x p lo rer 4+

D O M Level 1

lin k s[ ] T he link s in the page d efined by tags o f the fo rm < a h ref= ” lin k d est”> … < /a> .

N etscape 2+ and In te rnet E x p lo rer 3+

D O M Level 1

p lu g in s[ ] A ll the < em b ed > tags in a page . T h is co llection is synonym ous w ith em b ed s[ ] th e p referred co llection .

N etscape 3+ and In te rnet E x p lo rer 4+

N o D O M support

Web 4http://www.pint.com/classes/web4

�� � �� �� �� � � � �� ! "� � �� � � � � �� �

• document.anchors[ ] and document.links[ ]<a href="http://www.yahoo.com">Test Link</a><form><input type="button" value="change link" onclick="document.links[0].href='http://www.google.com'"></form>

• document.forms[ ] collection of <form> tags with action, method, name, etc. properties– elements[ ] collection within references the various

<input>, <textarea>, and <select> tags within the form– Demo

Web 4http://www.pint.com/classes/web4

�� � �� �� �� � � � �� ! "� � �� � � � � �� � �� ����

• The Images[ ] collection is similar with access to the attributes of the <img> tag.– Demo

• Given these basic objects it is possible to add simple form checking and navigation into Web pages using JavaScript

Web 4http://www.pint.com/classes/web4

� �� �# � ���� ����� � � �� �

• What to check?– Field blank– Field numeric– Field in range (min to max)– Field in some specified format (xxx-xx-xxx)

• Try to use form fields to keep errors from happening– State as 2 char text box vs a pull-down

• When should the form validation happen?– As the errors happen?– Between fields?– When the form is submitted?

Web 4http://www.pint.com/classes/web4

� �� �# � ���� ����� � � �� � �� ����

<form action=“dosomething.cgi”method=“post”onsubmit=“return validate( )”>

various fields<input type=“submit” value=“send”>

</form>• The function validate should be built to return true

if the fields are ok and false otherwise• Avoid using the script to perform the submit, the

action is for free and makes the form work when script is off

Web 4http://www.pint.com/classes/web4

� �� �# � ���� ����� � � �� � �� ����

• Do not reinvent the wheel many scripts are out there for years that will do more than you will ever need to do– http://developer.netscape.com/docs/examples/index.html?cont

ent=javascript.html

• See demos in Chapter 14 for the nitty gritty details of every type of form field and how it can be accessed– http://www.javascriptref.com/examples/ch14/index.htm

• Pay attention to the demos that improve form usability

Web 4http://www.pint.com/classes/web4

$ � !

• Form Checking Time– Create two fields one a text field and one a password

field– Create a page called success.htm that will be

displayed upon validation– Do a blank field check on the text field and make

sure that the password field equals the word “secret”

• Don’t forget code is online at javascriptref.com

Web 4http://www.pint.com/classes/web4

�� � � � �� � � �� �

• Netscape 3 introduced the Image object allowing access to objects inserted with the HTML <img>tag.

• Access Images via document.images[ ]– document.images[0]– document.images[‘imagename’]– document.imagename

• Under DOM this object is called the HTMLImageobject.

• The properties of Image are related to the attributes of the <img> tag as defined in HTML.

Web 4http://www.pint.com/classes/web4

P r o p e r t y D e s c r i p t i o n a l i g n I n d i c a t e s t h e a l i g n m e n t o f t h e i m a g e

u s u a l l y l e f t o r r i g h t a l t T h e a l t e r n a t i v e t e x t r e n d e r i n g f o r t h e i m a g e

s e t b y t h e a l t a t t r i b u t e b o r d e r T h e b o r d e r a r o u n d t h e i m a g e i n p i x e l s . c o m p l e t e A B o o l e a n v a l u e i n d i c a t i n g i f t h e i m a g e

h a s c o m p l e t e l y l o a d e d h e i g h t T h e h e i g h t o f t h e i m a g e d e f i n e d a s a p i x e l

o r p e r c e n t a g e v a l u e . h s p a c e T h e h o r i z o n t a l s p a c e a r o u n d t h e i m a g e . i s M a p B o o l e a n v a l u e i n d i c a t i n g p r e s e n c e o f

i s m a p a t t r i b u t e w h i c h i n d i c a t e s t h e i m a g e i s a s e r v e r - s i d e i m a g e m a p . T h e u s e M a p p r o p e r t y i s m o r e l i k e l y u s e d t o d a y .

l o n g D e s c T h e v a l u e o f t h e H T M L 4 l o n g d e s c a t t r i b u t e w h i c h p r o v i d e s a m o r e v e r b o s e d e s c r i p t i o n f o r t h e i m a g e t h a n t h e a l t a t t r i b u t e .

l o w s r c T h e U R L o f t h e “ l o w s o u r c e ” i m a g e a s s e t b y t h e l o w s r c a t t r i b u t e . U n d e r D O M L e v e l 1 t h i s i s s p e c i f i e d b y l o w S r c p r o p e r t y .

n a m e T h e v a l u e o f t h e n a m e a t t r i b u t e f o r t h e i m a g e .

s r c T h e U R L o f t h e i m a g e . u s e M a p T h e U R L o f t h e c l i e n t - s i d e i m a g e m a p i f

t h e < i m g > t a g h a s a u s e m a p a t t r i b u t e . v s p a c e T h e v e r t i c a l s p a c e i n p i x e l s a r o u n d t h e

i m a g e . w i d t h T h e w i d t h o f t h e i m a g e i n p i x e l s o r a s a

p e r c e n t a g e v a l u e .

Web 4http://www.pint.com/classes/web4

�� � � � �� � � �� � �� ����

• The image object also supports a few events (onabort, onerror, and onload). These are related to the cancellation, error, and loading of an image over the network. You will also find standard HTML event handlers like onmouseover, onclick, etc. available in HTML 4 and DOM aware browsers. Traditionally though often the event handlers for links around images were used for mouse detection.

Web 4http://www.pint.com/classes/web4

% ����&� �

• Since Nav3 creating a page embellishment called a rollover or “mouseover” image has been a common use for JavaScript

• The basic gist of the effect is to have an image for the on and off state and when the mouse goes over the image.

• Given <img src="image1.gif" name="myimage" id="myimage">

You might be tempted to try

<img src="image1.gif" name="myimage" id="myimage“onmouseover="document.myimage.src='image2.gif'“onmouseout="document.myimage.src='image1.gif'">

Or simply <img src=“image1.gif” onmouseover=“this.src=‘image2.gif’”onmouseout=“this.src=‘image1.gif’”>

Web 4http://www.pint.com/classes/web4

% ����&� � �� ����

• While the previous idea will work in a DOM compliant browser, it will fail in older browsers. It will also fail if the images that are being swapped are not downloaded before the user mouses over the region.

• To create bullet-proof rollovers you need– Detect for rollover capability (Image object available)– Make sure to preload images

• Secondarily we would want to create reusable code• To detect for a rollover available JavaScript implementation simply

detect for the Image object using a statement likeif (document.images)

{ // do rollover code

}• To preload we could create Image objects in the <head> of the

document forcing the download of the imagesvar offimage = new Image(90,90);offimage.src = “imageOff.gif”;

Web 4http://www.pint.com/classes/web4

% ����&� � �� ����

• We could then deal with preloading like so

if (document.images) {// preload imagesvar offimage = new Image(90,90); offimage.src = "imageoff.gif";var onimage = new Image(90,90); // for the active imageonimage.src = "imageon.gif";

}

• Of course now we need to deal with functions to flip the image on and off. The key to writing a generic routine would be the use of careful naming. Imagine adding the suffix On or Off to the end of an image (e.g. About) then we could calculate the image we are referring to automatically

Web 4http://www.pint.com/classes/web4

% ����&� � �� ����

if (document.images){ /* preload images */

var homeOn = new Image(); homeOn.src = "homeOn.gif"; var homeOff = new Image(); homeOff.src = "homeOff.gif";

var productsOn = new Image(); productsOn.src = "productsOn.gif"; var productsOff = new Image(); productsOff.src = "productsOff.gif";}

function mouseOn(imgName) {

if (document.images) document[imgName].src = eval(imgName + "On.src");

}

function mouseOff(imgName) {if (document.images)

document[imgName].src = eval(imgName + "Off.src");}

Web 4http://www.pint.com/classes/web4

% ����&� � �� ����

• The final issue is triggering the rollover. Under Netscape 3 level browsers we cannot detect mouseover on an <img>tag but we can test for it on an <a> tag thus often you see triggers like

<a href="home.html" onmouseover="mouseOn('home')"onmouseout="mouseOff('home')"><img src="homeOff.gif" height="50" width="100" name="home" border="0" alt="Home"></a>

<br><a href="products.html" onmouseover="mouseOn('products')"

onmouseout="mouseOff('products')"><img src="productsOff.gif" height="50" width="100" name="products" border="0" alt="Products"></a>

<br>

Web 4http://www.pint.com/classes/web4

$ � !

• Time for roll-over lab• In this lab create a simple page with three

rollover buttons use script code provided in class• Repeat the exercise using Dreamweaver• Add in CSS hover attributes to rollover links

Web 4http://www.pint.com/classes/web4

� � '����� � � �� �(� & � � ��

• Dynamic HTML or DHTML is when we begin to move page objects around or even modify the very HTML of the page itself. In some ways DHTML is just a particular usage of JavaScript particularly focused on use with CSS and it should not be thought of as a separate technology.

• There are two forms of DHTML: – 4.x generation browser style DHTML– DOM/W3C standard style DHTML

• Despite the focus on standards the 4.x generation approach is still widely employed

Web 4http://www.pint.com/classes/web4

� �) �� �������

• CSS-P and later CSS-2 introduces the ability to position objects at an arbitrary pixel location on the screen. Mastery of CSS is first required before using JavaScript to effect page look.

• Adding style to Web pages is relatively easy using linked style sheets (<link rel=“stylesheet”>), document wide sheets (<style> element), and the core attribute style which is common to most display elements (<p style=“color: green”>)

• Be careful to understand which CSS properties are supported across browsers. There are many holes!

• Oddly the position properties on the next slide are commonly supported.

Web 4http://www.pint.com/classes/web4

C S S P r o p e r t y D e s c r i p t i o n p o s i t i o n D e f i n e s t h e t y p e o f p o s i t i o n i n g u s e d f o r a n

e l e m e n t e i t h e r s t a t i c ( d e f a u l t ) , a b s o l u t e , r e l a t i v e , f i x e d , o r i n h e r i t . M o s t o f t e n a b s o l u t e i s u s e d t o s e t t h e e x a c t p o s i t i o n o f a n e l e m e n t r e g a r d l e s s o f d o c u m e n t f l o w .

t o p D e f i n e s t h e p o s i t i o n o f t h e o b j e c t f r o m t h e t o p o f t h e e n c l o s i n g r e g i o n . F o r m o s t o b j e c t s t h i s s h o u l d b e f r o m t h e t o p o f t h e b r o w s e r w i n d o w .

l e f t D e f i n e s t h e p o s i t i o n o f t h e o b j e c t f r o m t h e l e f t o f t h e e n c l o s i n g r e g i o n , m o s t o f t e n t h e l e f t o f t h e b r o w s e r w i n d o w i t s e l f .

h e i g h t D e f i n e s t h e h e i g h t o f a n e l e m e n t . W i t h p o s i t i o n e d i t e m s , a m e a s u r e i n p i x e l s ( p x ) i s o f t e n u s e d t h o u g h o t h e r s l i k e p e r c e n t a g e ( % ) a r e a l s o p o s s i b l e .

w i d t h D e f i n e s t h e w i d t h o f a n e l e m e n t . W i t h p o s i t i o n e d i t e m s , a m e a s u r e i n p i x e l s ( p x ) i s o f t e n u s e d .

c l i p A c l i p p i n g r e c t a n g l e l i k e c l i p : r e c t ( t o p r i g h t b o t t o m l e f t ) c a n b e u s e d t o d e f i n e a s u b s e t o f c o n t e n t t h a t i s s h o w n i n a p o s i t i o n e d r e g i o n a s d e f i n e d b y t h e r e c t a n g l e o f u p p e r l e f t c o r n e r a t t o p , l e f t a n d b o t t o m c o r n e r a t b o t t o m , r i g h t . N o t e t h a t t h e p i x e l v a l u e s o f t h e r e c t a n g l e a r e r e l a t i v e t o t h e c l i p p e d r e g i o n a n d n o t t h e s c r e e n .

v i s i b i l i t y S e t s w h e t h e r a n e l e m e n t s h o u l d b e h i d d e n . P o s s i b l e v a l u e s i n c l u d e h i d d e n , v i s i b l e , a n d i n h e r i t .

z - i n d e x D e f i n e s t h e s t a c k i n g o r d e r o f t h e o b j e c t . R e g i o n s w i t h h i g h e r z - i n d e x n u m b e r v a l u e s s t a c k o n t o p o f r e g i o n s w i t h l o w e r n u m b e r s . W i t h o u t z - i n d e x t h e o r d e r o f d e f i n i t i o n d e f i n e s s t a c k i n g , w i t h l a s t o b j e c t d e f i n e d t h e h i g h e s t u p .

Web 4http://www.pint.com/classes/web4

� �) �� �������

• A simple example of using CSS positioning properties can be found on page 527 and should be examined before proceeding

• While CSS-P is supported in > IE4 and > NS6, NS4 positioning is really accomplished with the <layer> tag and corresponding Layer object. Even when using CSS it maps into layers. The DOM works slightly differently so IE6 and NS6 probably should use DOM level code.

Web 4http://www.pint.com/classes/web4

� �� � �� ��� � �$ � ' � �

• To manipulate positioned regions which will generically call “layers” we need three approaches1. Netscape 4 with <layer> or <div> tags2. IE 4 with document.all[ ] and <div> tags3. DOM browsers with <div> tags

• Object detection for all three techniques can be accomplished like so(document.layers) ? layerobject=true : layerobject=false;(document.all) ? allobject = true: allobject = false;(document.getElementById) ? dom = true : dom = false;

Web 4http://www.pint.com/classes/web4

� �� � �� ��� � �$ � ' � � �� ����

• To create a layer library we create functions for basic functions including:

• function hide(layerName) { } • function show(layerName) { }• function setX(layerName, x) { } • function setY(layerName, y) { }• function setZ(layerName, zIndex) { } • function setHeight(layerName, height) { }• function setWidth(layerName, width) { }• function setClip(layerName, top, right, bottom, left) { }

function setContents( ) { }

Web 4http://www.pint.com/classes/web4

� �� � �� ��� � �$ � ' � �

• We need a special function that given a layername finds that “layer” in the document using the three methods.

function getElement(layerName,parentLayer) {

if(layerobject){

parentLayer = (parentLayer)? parentLayer : self;layerCollection = parentLayer.document.layers;if (layerCollection[layerName]) return layerCollection[layerName];/* look through nested layers */for (i=0; i < layerCollection.length;)

return(getElement(layerName, layerCollection[i++]));}

if (allobject) return document.all[layerName];if (dom) return document.getElementById(layerName);

}

Web 4http://www.pint.com/classes/web4

� �� � �� ��� � �$ � ' � �

Individual functions then can be built for each feature.

function hide(layerName){

var theLayer = getElement(layerName);if (layerobject)

theLayer.visibility = 'hide';else

theLayer.style.visibility = 'hidden';}

function show(layerName){

var theLayer = getElement(layerName);if (layerobject)

theLayer.visibility = 'show';else

theLayer.style.visibility = 'visible';}

Web 4http://www.pint.com/classes/web4

� �� � �� ��� � �$ � ' � �

• A complete layer library is presented from pages 536-539 in JavaScript Reference with a test page on pages 540-541. Readers should type this in and test it before proceeding.

• Numerous libraries are online to help with cross browser animations – www.cross-browser.com– http://dynapi.sourceforge.net/dynapi/– http://www.dithered.com/experiments/1kdhtml/index.html

Web 4http://www.pint.com/classes/web4

� � ����

• The W3C DOM aims to create some standards out of the havoc of 4.x generation browser DHTML

• It does require a stricter approach to our HTML and JavaScript and has some clunkiness in some places

• It too needs libraries to make things easy– Example: http://www.domapi.com

Web 4http://www.pint.com/classes/web4

� � �� �� &��

• The Document Object Model or DOM is a standard that maps HTML and XML documents into objects for manipulation by scripting languages such as JavaScript

• The DOM comes in the following flavors:– DOM Level 0 – roughly equivalent to NS3’s object model. Often

called traditional or classic object model– DOM Level 1 – Maps all the HTML elements and provides generic

“node” manipulation features via the document object. – DOM Level 2 – Maps all CSS properties

Note: The later DOM levels also support the earlier objects so “classic”scripts should work under DOM

Web 4http://www.pint.com/classes/web4

� � �� �� &�� �� ����

• Another breakdown of the DOM is– DOM Core – core features for node manipulation (create, delete,

movement, etc.)– DOM HTML – bindings to HTML tags (HTMLParagraph, etc.)– DOM CSS – bindings to CSS properties– DOM Events – event handling support– DOM XML – bindings to deal with user defined XML languages

• Today’s modern browsers like IE 5+ and NS 6+ support DOM Core, DOM HTML, and a good portion of DOM CSS. However, DOM events and DOM XML are not consistently supported

Web 4http://www.pint.com/classes/web4

� �� � � � ��� � � �

• The key to understanding the DOM is how an HTML document is modeled as a tree. Consider

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">

<html><head><title>DOM Test</title></head><body><h1>DOM Test Heading</h1><hr><!-- Just a comment --><p>A paragraph of <em>text</em> is just an example</p><ul>

<li><a href="http://www.yahoo.com">Yahoo!</a></li></ul></body></html>

Web 4http://www.pint.com/classes/web4

� ��� �� ��� �� � � � ��� � �

Web 4http://www.pint.com/classes/web4

$ ��* ��� �� �� � �� � �

• The tree structure follows the structured nature of HTML. <html> tags encloses <head> and <body>. <head> encloses <title> and so on.

• Each of the items in the tree is called generically a node

• Notice that are different types of nodes corresponding to HTML elements, text strings, and even comments. The types of nodes relevant to most JavaScript programmers is shown on the next slide.

Web 4http://www.pint.com/classes/web4

+ ��� �% � �� ���� � �� �

• Look at the tree for <p>A paragraph of <em>text</em> is just an example</p>

Notice that the <p> tag has three direct children and one“grandchild” Also make sure you understand thesibling and parent relationships. The DOM relies on them

Web 4http://www.pint.com/classes/web4

+ ��� �% � �� ���� � �� � �� ����

Web 4http://www.pint.com/classes/web4

, � � � � � ��� �+ ��� �

• The easiest way to access nodes in a document tree is via the getElementById( )method for the Document object.

• In order to use the method we need to name our tags using the HTML 4 core attribute idlike so<p id="p1" align="center">A paragraph of <em>text</em> is just an example</p>

Web 4http://www.pint.com/classes/web4

, � � � � � ��� �+ ��� � �� ����

• Using document.getElementById(‘p1’) we are returned an DOM Element object that corresponds to the appropriate node in the tree.

var currentElement = document.getElementById('p1');var msg = "nodeName: "+currentElement.nodeName+"\n";msg += "nodeType: "+currentElement.nodeType+"\n";msg += "nodeValue: "+currentElement.nodeValue+"\n";alert(msg);

Web 4http://www.pint.com/classes/web4

, � � � � � ��� �+ ��� � �� ����

• Notice the node value to be 1 (an element), the type P corresponding to the HTML <p>tag, and the nodeValue is null.

• The reason for the null value is that you have to look at a text node to see the text within the parent tag. We now need to learn how to move around the tree. Fortunately there are some generic node properties that make this very easy as summarized on the next slide.

Web 4http://www.pint.com/classes/web4

� � �+ ��� �) �� � �� �

D O M N o d e P ro p er tie s D escr ip tio n

n o d eN am e C o n ta in s th e n am e o f th e n o d e n o d eV a lu e C o n ta in s th e v a lu e w ith in th e n o d e ,

g en e ra lly o n ly ap p lic ab le to tex t n o d es n o d eT yp e H o ld s a n u m b er co rre sp o n d in g to th e typ e

o f n o d e , a s g iv en in T ab le 1 0 -1 p a ren tN o d e A re fe ren ce to th e p a ren t n o d e o f th e

cu rren t o b jec t, if o n e ex is ts ch ild N o d es A ccess to l is t o f ch ild n o d es f irs tC h ild R e fe ren ce to th e firs t ch ild n o d e o f th e

e lem en t, if o n e ex is ts la s tC h ild P o in ts to th e la s t ch ild n o d e o f th e e lem en t,

if o n e ex is ts p rev io u sS ib lin g R e fe ren ce to th e p rev io u s s ib lin g o f th e

n o d e ; fo r ex am p le , if its p a ren t n o d e h a s m u ltip le ch ild ren

n ex tS ib lin g R e fe ren ce to th e n ex t s ib lin g o f th e n o d e ; fo r ex am p le , if i ts p a ren t n o d e h a s m u ltip le ch ild ren

a ttr ib u te s T h e lis t o f th e a ttr ib u te s fo r th e e lem en t o w n e rD o cu m en t P o in ts to th e H T M L D o cu m en t o b jec t in

w h ich th e e lem en t is co n ta in ed

Web 4http://www.pint.com/classes/web4

� � � �� �� �&� � � �

• Using the common node properties you should be able to move around a tree that you know the structure of

• var currentElement = document.getElementById(‘p1’);currentElement = currentElement.firstChild;currentElement = currentElement.nextSibling;currentElement = currentElement.parentNode;

• This simple script would end up right were it started from assuming that the starting node had at least two children.

Web 4http://www.pint.com/classes/web4

� � � ��� �+ ��� �

• You can create nodes and then insert them into the document treenewNode = document.createElement(‘p’);

• Of course you may have to then create text nodes to put inside of elementsnewText = document.createTextNode(‘Hello there’);

• Then we will attach things together and attachtothe documentnewNode.appendChild(newText);document.body.appendChild(newNode);

Web 4http://www.pint.com/classes/web4

� � � � �+ ��� �� � � ���

Method Description Example

createAttribute(name); Creates an attribute for an element specified by the string name. Rarely used with existing HTML elements since they have predefined attribute names that can be manipulated directly.

myAlign = document.createAttribute(“align”);

createComment(string); Creates an HTML/XML text comment of the form <!-- string --> where string is the comment content.

myComment = document.createComment(“Just a comment”);

createElement(tagName) Creates an element of the type specified by the string parameter tagName

myHeading = document.createElement(“h1”);

createTextNode(string) Creates a text node containing string.

newText = document.createTextNode(“Some new text”);

Web 4http://www.pint.com/classes/web4

��� � �� ���, � � � ���� � � ���

• The two methods for node attaching are insertBefore(newChild, referenceChild) and appendChild(newChild)

• These methods run on a node object, for example

newText = document.createTextNode(‘Hi!’);currentElement = document.body;insertPt = document.getElementById(‘p1’);currentElement.insertBefore(insertPt,newText);

Web 4http://www.pint.com/classes/web4

� � �� ��� �+ ��� �

• The Node object’s removeChild(child) method is useful to delete a node out of the tree. You need to run this node on the parent of the object you are interested in deleting

var current = getElementById(‘p1’);currentParent = current.parentNode;currentParent.removeChild(current);

• Note: The removeChild( ) method does return the node object removed.

Web 4http://www.pint.com/classes/web4

� ���-' ��� �+ ��� �

• You can’t modify an element directly but you can modify its contents particularly text nodes. Given

<p id=“p1”>This is a test</p>Use

textNode = document.getElementById(‘p1’).firstChild;then set the textNode’s data property

textNode.data = “I’ve been changed!”;

• There are a variety of DOM methods like appendData( ), deleteData( ), insertData( ), replaceData( ), splitText( ), and substringData( ) that can be used, but since the data value is just a string you might want to resort to commonly understood String object methods.

Web 4http://www.pint.com/classes/web4

� ���-' ��� �, �! � � �

• Attributes can be manipulated by DOM methods like getAttribute(name), setAttribute(attributename, attributevalue) and removeAttribute(attributeName) that work off a particular Node object. You can also check for the existence of attributes using the hasAttributes( )method.

• Most people do not use these DOM methods but directly modify the attributes of the tag like so

<p id=“p1” align=“left”>This is a test</p>• You would use

current = document.getElementById(‘p1’);current.align = ‘right’;

Web 4http://www.pint.com/classes/web4

� � � �� � �� ���. � � $

• What you should begin to recognize now is the key to the DOM in most Web pages is understanding HTML

• The various properties of a node correspond directly to its HTML attributes. For example given a paragraph tag <p>it corresponds to an HTMLParagraphElement with the following properties align, id, className, title, lang, and dir. Notice the mapping from HTML attributes to object properties is nearly one-to-one except for some situations like the class attribute which would be a reserved word and thus is renamed className under the DOM.

• Two word attributes like tabindex are represented in the DOM in typical programming camel back form (e.g. tabIndex)

Web 4http://www.pint.com/classes/web4

� � � �� � �� ���. � � $

• The ramification of this relationship between HTML and JavaScript via the DOM is that the language can now manipulate any arbitrary HTML element in anyway, but it does require a well formed document otherwise the results can be somewhat unpredictable

• Suddenly, knowing how to do HTML properly actually matters. Even WYSIWYG editors will have to modified to ensure 100% validatable markup to ensure correct JavaScript operation

• The intersection with CSS is very similar and covered under DOM Level 2

Web 4http://www.pint.com/classes/web4

� � � �� � �� ����

• The style attribute for an HTML element allows style sheets properties to be set inline. The DOM allows access to this attribute’s value, for example given

<p id=“p1” style=“color: red”>Test</p>

then

theElement = document.getElementById(‘p1’);theElement.style.color = ‘green’;

• What we see is like HTML the various CSS properties map to DOM names directly, so font-size becomes fontSize, background-color becomes backgroundColor, and so on. There are only one or two exceptions to this conversion.

Web 4http://www.pint.com/classes/web4

� � �� ��� �� � ����

• The DOM represents the possibility for easier cross-browser scripting, but it also requires mastery of CSS and HTML to be used properly

• Some aspects of the BOM are actually easier to use than the DOM– Consider creating nodes or manipulating text contents,

some programmers find using properties like innerHTML, innerText, outerText, and outerHTML to be far easier than making nodes one by one

• A great deal of legacy code using BOM objects like IE’s document.all[ ] style exist and would have to be ported. This will take time!

Web 4http://www.pint.com/classes/web4

(� & � � �� �. �� � ��*

• Three JavaScript Examples– You have to have three working realistic JavaScript

examples that are cleaned-up and made as standard and well formed as possible

• A contract form with validation• Rollover buttons• A menu system

– You may use sites like dynamicdrive.com and others to start you off