1 introduction to web application implement javascript in html
TRANSCRIPT
1
Introduction to Web Application
Implement JavaScript in HTML
2
References
• http://10.89.115.100:8086/material/JavaScriptBibleGoldEn.pdf
• Web Development/HTML and Dynamic HTML/DHTML Reference
• http://www.w3.org/DOM
3
Introduction• Dynamic HTML Object Model
– Allows Web authors to control the presentation of their pages
– Gives them access to all the elements on their pages
• Web page– Elements, forms, frames, tables
– Represented in an object hierarchy
• Scripting– Retrieve and modify properties and attributes
4
Object Referencing• The simplest way to reference an element is by
using the element’s id attribute.• The element is represented as an object
– HTML attributes become properties that can be manipulated by scripting
5
Example of all<html> <head> <title>Object Model</title> <script type = "text/javascript"> <!--
function start() { alert( pText.innerText ); pText.innerText = "Thanks for coming."; } // --> </script>
</head> <body onload = "start()"> <p id = "pText">Welcome to our Web page!</p> </body></html>
6
7
Collections all and children• Collections
– Arrays of related objects on a page
– all• all the HTML elements in a document
– children• Specific element contains that element’s child elements
8
<html> <head> <title>Object Model</title> <script type = "text/javascript"> <!--
var elements = ""; function start() { for ( var loop = 0; loop < document.all.length; ++loop ) elements += "<br />" + document.all[ loop ].tagName; pText.innerHTML += elements; alert( elements ); } // --> </script> </head>
<body onload = "start()"> <p id = "pText">Elements on this Web page:</p> </body></html>
9
10
<html> <head> <title>Object Model</title> <script type = "text/javascript"> <!--
var elements = "<ul>"; function child( object ) { var loop = 0; elements += "<li>" + object.tagName + "<ul>"; for ( loop = 0; loop < object.children.length; loop++ ) { if ( object.children[ loop ].children.length ) child( object.children[ loop ] ); else elements += "<li>" + object.children[ loop ].tagName + "</li>"; } elements += "</ul>" + "</li>"; } // --> </script> </head>
11
<body onload = "child( document.all[ 4 ] );
myDisplay.outerHTML += elements;
myDisplay.outerHTML += '</ul>';">
<p>Welcome to our <strong>Web</strong> page!</p>
<p id = "myDisplay">
Elements on this Web page:
</p> </body>
</html>
12
The Document Object Model
• The DOM is an abstract model that defines the interface between HTML documents and application programs
• Documents in DOM have a tree-like structure
13
The Document Object Model
14
The Document Object Model• Under development by w3c since the mid-90s• DOM is a successor to DHTML• DOM now has 4 levels• DOM0 is designed to deal with just HTML
documents• DOM1 is focused on the HTML and XML
document model, all modern browser has supported DOM1– Appendix
15
The Document Object Model
• DOM 2 is the latest approved standard, which specifies a CSS object model and include document traversals and an event model, but none modern browser can fully support DOM2
• DOM3 is under development
16
The Document Object Model• It is an OO model - document elements are
objects• A language that supports the DOM must
have a binding to the DOM constructs• In the JavaScript binding, HTML elements
are represented as objects and element attributes are represented as properties– e.g., <input type = "text" name = "address">
would be represented as an object with two properties, type and name, with the values "text" and "address"
17
The Document Object Model
• The property names in JavaScript are usually just lowercase versions of the corresponding HTML attribute names
18
Dynamic Styles
• Element’s style can be changed dynamically• Dynamic HTML Object Model also allows you to
change the class attribute
19
<html > <head> <title>Object Model</title> <script type = "text/javascript"> <!--
function start() { var inputColor = prompt( "Enter a color name for the " + "background of this page", "" ); document.body.style.backgroundColor = inputColor; } // --> </script> </head>
<body onload = "start()"> <p>Welcome to our Web site!</p> </body></html>
20
21
<html> <head> <title>Object Model</title>
<style type = "text/css">
.bigText { font-size: 3em; font-weight: bold } .smallText { font-size: .75em }
</style> <script type = "text/javascript"> <!-- function start() { var inputClass = prompt( "Enter a className for the text " + "(bigText or smallText)", "" );
pText.className = inputClass; } // --> </script> </head>
<body onload = "start()">
<p id = "pText">Welcome to our Web site!</p> </body></html>
22
23
Dynamic Positioning
• HTML elements can be positioned with scripting– Declare an element’s CSS position property to be either absolute or relative
– Move the element by manipulating any of the top, left, right or bottom CSS properties
24
<html> <head> <title>Dynamic Positioning</title> <script type = "text/javascript"> <!--
var speed = 5; var count = 10; var direction = 1; var firstLine = "Text growing"; var fontStyle = [ "serif", "sans-serif", "monospace" ]; var fontStylecount = 0; function start() { window.setInterval( "run()", 100 ); }
function run()….. // --> </script>
</head> <body onload = "start()"> <p id = "pText" style = "position: absolute; left: 0; font-family: serif; color: blue"> Welcome!</p> </body></html>
25
function run() { count += speed; if ( ( count % 200 ) == 0 ) { speed *= -1; direction = !direction; pText.style.color = ( speed < 0 ) ? "red" : "blue" ; firstLine = ( speed < 0 ) ? "Text shrinking" : "Text growing"; pText.style.fontFamily = fontStyle[ ++fontStylecount % 3 ]; } pText.style.fontSize = count / 3; pText.style.left = count; pText.innerHTML = firstLine + "<br /> Font size: " + count + "px"; }
26
27
Using the frames Collection
• Referencing elements and objects in different frames by using the frames collection
28
Index.html
<html>
<head>
<title>Frames collection</title>
</head>
<frameset rows = "100, *">
<frame src = "top.html" name = "upper" />
<frame src = "" name = "lower" />
</frameset>
</html>
29
top.html<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>The frames collection</title> <script type = "text/javascript"> <!--
function start() { var text = prompt( "What is your name?", "" ); parent.frames( "lower" ).document.write( "<h1>Hello, " + text + "</h1>" ); } // --> </script> </head>
<body onload = "start()"> <h1>Cross-frame scripting!</h1> </body></html>
30
31
navigator Object
• Netscape, Mozilla, Microsoft’s Internet Explorer– Others as well
• Contains information about the Web browser• Allows Web authors to determine what browser
the user is using
32
<html> <head> <title>The navigator Object</title> <script type = "text/javascript"> <!--
function start() { if ( navigator.appName == "Microsoft Internet Explorer" ) { if ( navigator.appVersion.substring( 1, 0 ) >= "4" ) document.location = "newIEversion.html"; else document.location = "oldIEversion.html"; } else document.location = "NSversion.html"; } // --> </script> </head>
<body onload = "start()"> <p>Redirecting your browser to the appropriate page, please wait...</p> </body></html>
33
Summary of the DHTML Object Model
applets
all
anchors
embeds
forms
filters
images
links
plugins
styleSheets
scripts
frames
plugins
collection
body
screen
document
history
navigator
location
event
document
document
object
window
Key
Fig. 13.10 DHTML Object Model.
34
Summary of the DHTML Object Model
Object or collection Description Objects
window Represents the browser window and provides access to the document object contained in the window. If the window contains frames a separate window object is created automatically for each frame, to provide access to the document rendered in the frame. Frames are considered to be subwindows in the browser.
document Represents the XHTML document rendered in a window. The document object provides access to every element in the XHTML document and allows dynamic modification of the XHTML document.
body Provides access to the body element of an XHTML document. history Keeps track of the sites visited by the browser user. The object provides a script
programmer with the ability to move forward and backward through the visited sites, but for security reasons does not allow the actual site URLs to be manipulated.
navigator Contains information about the Web browser, such as the name of the browser, the version of the browser, the operating system on which the browser is running and other information that can help a script writer customize the user’s browsing experience.
location Contains the URL of the rendered document. When this object is set to a new URL, the browser immediately switches (navigates) to the new location.
event Can be used in an event handler to obtain information about the event that occurred (e.g., the mouse x-y coordinates during a mouse event).
screen Contains information about the computer screen for the computer on which the browser is running. Information such as the width and height of the screen in pixels can be used to determine the size at which elements should be rendered in a Web page.
Fig. 13.11 Objects in the Internet Explorer 6 Object Model.
35
Summary of the DHTML Object ModelObject or collection Description Collections
all Many objects have an all collection that provides access to every element contained in the object. For example, the body object’s all collection provides access to every element in the body element of an XHTML document.
anchors Collection contains all the anchor elements (a) that have a name or id attribute. The elements appear in the collection in the order they were defined in the XHTML document.
applets Contains all the applet elements in the XHTML document. Currently, the most common applet elements are Java applets.
embeds Contains all the embed elements in the XHTML document.
forms Contains all the form elements in the XHTML document. The elements appear in the collection in the order they were defined in the XHTML document.
frames Contains window objects that represent each frame in the browser window. Each frame is treated as its own subwindow.
images Contains all the img elements in the XHTML document. The elements appear in the collection in the order they were defined in the XHTML document.
links Contains all the anchor elements (a) with an href property. This collection also contains all the area elements that represent links in an image map.
Fig. 13.11 Objects in the Internet Explorer 6 Object Model.
36
Summary of the DHTML Object Model
Object or collection Description plugins Like the embeds collection, this collection contains all the embed elements in the
XHTML document. scripts Contains all the script elements in the XHTML document.
styleSheets Contains styleSheet objects that represent each style element in the XHTML document and each style sheet included in the XHTML document via link.
Fig. 13.11 Objects in the Internet Explorer 6 Object Model.
37
Event Model
38
Introduction
• Event model– Scripts can respond to user– Content becomes more dynamic– Interfaces become more intuitive
39
Event onclick• onClick
– Invoked when user clicks the mouse on a specific item
40
<html> <head> <title>DHTML Event Model - onclick</title>
<script type = "text/javascript" for = "para" event = "onclick">
<!-- alert( "Hi there" ); // --> </script> </head> <body>
<!-- The id attribute gives a unique identifier --> <p id = "para">Click on this text!</p> <!-- You can specify event handlers inline --> <input type = "button" value = "Click Me!" onclick = "alert( 'Hi again' )" /> </body></html>
41
42
Event onload
• onload event– Fires when an element finishes loading– Used in the body element– Initiates a script after the page loads into the
client
43
<html> <head> <title>DHTML Event Model - onload</title> <script type = "text/javascript"> <!--
var seconds = 0; function startTimer() { // 1000 milliseconds = 1 second window.setInterval( "updateTime()", 1000 ); } function updateTime() { seconds++; soFar.innerText = seconds; } // --> </script> </head>
<body onload = "startTimer()"> <p>Seconds you have spent viewing this page so far: <strong id = "soFar">0</strong></p> </body></html>
44
45
Error Handling with onerror
• onerror event– Execute specialized error-handling code
46
<html> <head> <title>DHTML Event Model - onerror</title> <script type = "text/javascript"> <!--
window.onerror = handleError; function doThis() { alrrt( "hi" ); // alert misspelled, creates an error } function handleError( errType, errURL, errLineNum ) { window.status = "Error: "+errType + " on line " +
errLineNum; return true; } // --> </script> </head> <body>
<input id = "mybutton" type = "button" value = "Click Me!" onclick = "doThis()" /> </body></html>
47
48
Tracking the Mouse with Event onmousemove
• onmousemove– Fires repeatedly when the user moves the
mouse over the Web page– Gives position of the mouse
49
<html> <head> <title>DHTML Event Model - onmousemove event</title>
<script type = "text/javascript"> <!-- function updateMouseCoordinates() { coordinates.innerText = event.srcElement.tagName + " (" + event.offsetX + ", " + event.offsetY + ")"; } // --> </script> </head>
<body style = "background-color: wheat" onmousemove = "updateMouseCoordinates()">
<span id = "coordinates">(0, 0)</span><br /> <img src = "deitel.gif" style = "position: absolute; top: 100; left: 100" alt = "Deitel" /> </body></html>
50
51
Rollovers with onmouseover and onmouseout
• Two more events fired by mouse movements– onmouseover
• Mouse cursor moves over element
– Onmouseout• Mouse cursor leaves element
52
<html> <head> <title> DHTML Event Model - onmouseover and onmouseout </title> <script type = "text/javascript"> <!--
captionImage1 = new Image(); captionImage1.src = "caption1.gif"; captionImage2 = new Image(); captionImage2.src = "caption2.gif"; function mOver() { if ( event.srcElement.id == "tableCaption" ) { event.srcElement.src = captionImage2.src; return; } if ( event.srcElement.id ) event.srcElement.style.color =
event.srcElement.id; }
53
function mOut() { if ( event.srcElement.id == "tableCaption" ) { event.srcElement.src = captionImage1.src; return; } if ( event.srcElement.id ) event.srcElement.innerText = event.srcElement.id; } document.onmouseover = mOver; document.onmouseout = mOut; // --> </script> </head>
54
<body style = "background-color: wheat"> <h1>Guess the Hex Code's Actual Color</h1> <p>Can you tell a color from its hexadecimal RGB code value? Look at the hex code, guess the color. To see what color it corresponds to, move the mouse over the hex code. Moving the mouse out will display the color name.</p> <table style = "width: 50%; border-style: groove; text-align: center; font-family: monospace; font-weight: bold">
<caption> <img src = "caption1.gif" id = "tableCaption" alt =
"Table Caption" /> </caption> <tr> <td id = "Black">#000000</td> <td id = "Blue">#0000FF</td> <td id = "Magenta">#FF00FF</td> <td id = "Gray">#808080</td> </tr> </table> </body></html>
55
56
Rollovers with onmouseover and onmouseout
Property of event Description altkey This value is true if Alt key was pressed when event fired.
button Returns which mouse button was pressed by user (1: left-mouse button, 2: right-mouse button, 3: left and right buttons, 4: middle button, 5: left and middle buttons, 6: right and middle buttons, 7: all three buttons).
cancelBubble Set to false to prevent this event from bubbling (see Section 14.9, “Event Bubbling”).
clientX / clientY The coordinates of the mouse cursor inside the client area (i.e., the active area where the Web page is displayed, excluding scrollbars, navigation buttons, etc.).
ctrlKey This value is true if Ctrl key was pressed when event fired. offsetX / offsetY The coordinates of the mouse cursor relative to the object that fired the event.
propertyName The name of the property that changed in this event. recordset A reference to a data field’s recordset (see Chapter 16, “Data Binding”). returnValue Set to false to cancel the default browser action. screenX / screenY The coordinates of the mouse cursor on the screen coordinate system. shiftKey This value is true if Shift key was pressed when event fired. srcElement A reference to the object that fired the event. type The name of the event that fired. x / y The coordinates of the mouse cursor relative to this element’s parent
element. Fig. 14.5 Some event object properties.
57
Form Processing with onfocus and onblur
• onfocus event fires when element gains focus
• onblur event fires when element loses focus
58
<html> <head> <title>DHTML Event Model - onfocus and onblur</title> <script type = "text/javascript"> <!--
var helpArray = […]; function helpText( messageNum ) { myForm.helpBox.value = helpArray[ messageNum ]; } // --> </script> </head> <body>
<form id = "myForm" action = ""> Name: <input type = "text" name = "name" onfocus = "helpText(0)" onblur = "helpText(6)" /><br />….</form> </body></html>
59
60
More Form Processing with onsubmit and onreset
• onsubmit and onreset are useful events for processing forms
61
<html> <head> <title> DHTML Event Model - onsubmit and onreset events </title> <script type = "text/javascript"> <!--
function formSubmit() { window.event.returnValue = false; if ( confirm ( "Are you sure you want to submit?" ) ) window.event.returnValue = true; } function formReset() { window.event.returnValue = false; if ( confirm( "Are you sure you want to reset?" ) ) window.event.returnValue = true; } // --> </script> </head>
62
<body> <form id = "myForm" onsubmit = "formSubmit()" onreset = "formReset()" action = ""> Name: <input type = "text" name = "name" onfocus = "helpText(0)" onblur = "helpText(6)"
/><br /> <input type = "submit" value = "Submit" onfocus = "helpText(4)" onblur = "helpText(6)" /> <input type = "reset" value = "Reset" onfocus = "helpText(5)" onblur = "helpText(6)" /> </form> </body></html>
63
64
Event Bubbling
• Crucial part of the event model
• Process whereby events fired in child elements “bubble” up to their parent elements
65
<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>DHTML Event Model - Event Bubbling</title> <script type = "text/javascript"> <!--
function documentClick() { alert( "You clicked in the document" ); } function paragraphClick( value ) { alert( "You clicked the text" ); if ( value ) event.cancelBubble = true; } document.onclick = documentClick; // --> </script> </head> <body>
<p onclick = "paragraphClick( false )">Click here!</p> <p onclick = "paragraphClick( true )">Click here, too!</p> </body></html>
66
67
More DHTML Events
• Remaining DHTML events and their descriptions
68
More DHTML EventsEvent Description Clipboard events
onbeforecut Fires before a selection is cut to the clipboard. onbeforecopy Fires before a selection is copied to the clipboard. onbeforepaste Fires before a selection is pasted from the clipboard. oncopy Fires when a selection is copied to the clipboard. oncut Fires when a selection is cut to the clipboard. onabort Fires if image transfer has been interrupted by user. onpaste Fires when a selection is pasted from the clipboard. Data binding events onafterupdate Fires immediately after a databound object has been updated. onbeforeupdate Fires before a data source is updated. oncellchange Fires when a data source has changed. ondataavailable Fires when new data from a data source become available. ondatasetchanged Fires when content at a data source has changed. ondatasetcomplete Fires when transfer of data from the data source has
completed. onerrorupdate Fires if an error occurs while updating a data field. onrowenter Fires when a new row of data from the data source is
available. onrowexit Fires when a row of data from the data source has just
finished. onrowsdelete Fires when a row of data from the data source is deleted. onrowsinserted Fires when a row of data from the data source is inserted. Fig. 14.10 Dynamic HTML events.
69
More DHTML EventsEvent Description Keyboard events
onhelp Fires when the user initiates help (i.e., by pressing the F1 key). onkeydown Fires when the user pushes down a key. onkeypress Fires when the user presses a key. onkeyup Fires when the user ends a key press. Marquee events onbounce Fires when a scrolling marquee bounces back in the other
direction. onfinish Fires when a marquee finishes its scrolling. onstart Fires when a marquee begins a new loop. Mouse events oncontextmenu Fires when the context menu is shown (right-click). ondblclick Fires when the mouse is double clicked. ondrag Fires during a mouse drag. ondragend Fires when a mouse drag ends. ondragenter Fires when something is dragged onto an area. ondragleave Fires when something is dragged out of an area. ondragover Fires when a drag is held over an area. ondragstart Fires when a mouse drag begins.
ondrop Fires when a mouse button is released over a valid target during a drag.
onmousedown Fires when a mouse button is pressed down. Fig. 14.10 Dynamic HTML events.
70
More DHTML EventsEvent Description onmouseup Fires when a mouse button is released. Miscellaneous events onafterprint Fires immediately after the document prints. onbeforeeditfocus Fires before an element gains focus for editing. onbeforeprint Fires before a document is printed. onbeforeunload Fires before a document is unloaded (i.e., the window was closed or a link was
clicked). onchange Fires when a new choice is made in a select element, or when a text input is
changed and the element loses focus. onfilterchange Fires when a filter changes properties or finishes a transition (see Chapter 15,
Dynamic HTML: Filters and Transitions). onlosecapture Fires when the releaseCapture method is invoked. onpropertychange Fires when the property of an object is changed. onreadystatechange Fires when the readyState property of an element
changes. onreset Fires when a form resets (i.e., the user clicks a reset button). onresize Fires when the size of an object changes (i.e., the user resizes a window or frame). onscroll Fires when a window or frame is scrolled. onselect Fires when a text selection begins (applies to input or
textarea). onselectstart Fires when the object is selected. onstop Fires when the user stops loading the object. onunload Fires when a page is about to unload.
Fig. 14.10 Dynamic HTML events.