Lecture 9: JavaScript and HTML
Ouissem Ben Fredj
[email protected] http://lms.tu.edu.sa/
502261-3 – Web Systems
Taif University
College of Computers and Information Technology
JavaScript and DOM
● JavaScript relies on a Document Object Model (DOM)
that describes the structure of the web page
● You can do a lot with a just a little understanding of the
DOM
● You use the DOM to access elements on the web page
● You can capture events without knowing the DOM at all
● You need the DOM to make any changes to the web page
0
Methods to access data
● Use the JavaScript getElementById ("id") method.
● In practice, every item (like input boxes, textboxes, etc)
should be given both a name and an id (except for forms
in the Strict XHTML).
● You can use also getElementByName("name")
Using getElementById
<html><head> <title> Fun with Text Boxes </title>
<style> .error{color:red;}</style>
<script type="text/javascript">
function FahrToCelsius(){
errorMsgid = document.getElementById('errorMsg');
errorMsgid.innerHTML = "";
var F=document.getElementById('Fahr');
var C=document.getElementById('Celsius');
if (!isNaN(parseFloat(F.value))) {
C.value = (5/9)*(parseFloat(F.value)- 32);
F.style.color = "green";
}else{
errorMsgid.innerHTML = "Please enter a Fahrenheit temperature!";
errorMsgid.className="error"; C.value = "";F.style.color= “red";
}
}
</script>
</head>
<body>
<form id="BoxForm" action="">
<p><label for="Fahr">Temperature in Fahrenheit:</label>
<input type="text" name ="Fahr" id="Fahr" size="10" value="0"
onchange="FahrToCelsius();" /> <span id="errorMsg"></span><br />
<input type="text" name="Celsius" id="Celsius" size="10" value=""
onfocus="getElementById('Fahr').focus();" /> in Celsius </p>
</form> </body></html>
Events
● Some elements on the web page respond to user
interactivity (keystrokes, mouse clicks) by creating
events
● Different kinds of elements produce different events
● We will concentrate on events from HTML form elements
and commonly recognized events
● You can put handlers on HTML form elements
0
A simple event handler
● <form method="post" action="">
<input type="button"
name="myButton"
value="Click me"
onclick="alert('You clicked the button!');">
</form>
● The button is enclosed in a form
● method tells how to send the form data; action tells where to send it
● The tag is input with attribute type="button"
● The name can be used by other JavaScript code
● The value is what appears on the button
● onclick is the name of the event being handled
● The value of the onclick element is the JavaScript code to execute
● alert : JavaScript code that pops up an alert box with the given text
0
Capitalization
● JavaScript is case sensitive
● HTML is not case sensitive
● onclick="alert('You clicked the button!');"
● The red underlined parts are HTML
● The quoted string is JavaScript
● You will frequently see onclick capitalized as onClick
● The Java naming convention is easier to read
● This is fine in HTML, but an error if it occurs in JavaScript
● Also note: Since we have a quoted string inside
another quoted string, we need both single and
double quotes
0
Common events
● Most HTML elements produce the following events:
● onClick -- the form element is clicked
● onDblClick -- the form element is clicked twice in close succession
● onMouseDown -- the mouse button is pressed while over the form element
● onMouseOver -- the mouse is moved over the form element
● onMouseOut -- the mouse is moved away from the form element
● onMouseUp -- the mouse button is released while over the form element
● onMouseMove -- the mouse is moved
● In JavaScript, these must be spelled in all lowercase
0
Example: Simple rollover
● The following code will make the text Hello
red when the mouse moves over it, and
blue when the mouse moves away
<h1 onMouseOver="style.color='red';"
onMouseOut="style.color='blue';">Hello </h1>
● Image rollovers are just as easy:
<img src="../Images/duke.gif"
width="55" height="68"
onMouseOver="src='../Images/duke_wave.gif';"
onMouseOut="src='../Images/duke.gif';">
0
Events and event handlers I
● The following tables are taken from:
http://developer.netscape.com/docs/manuals/js/client/
jsguide/index.htm
Event Applies to Occurs when Handler
Load Document body User loads the page in a onLoad
browser
Unload Document body User exits the page onUnload
Error Images, window Error on loading an onError
image or a window
Abort Images User aborts the loading onAbort
of an image
0
Events and event handlers II
Event Applies to Occurs when Handler
KeyDown Documents, images, User depresses a onKeyDown
links, text areas key
KeyUp Documents, images, User releases a onKeyUp
links, text areas key
KeyPress Documents, images, User presses or onKeyPress
links, text areas holds down a key
Change Text fields, text areas, User changes the onChange
select lists value of an
element
0
Events and event handlers III
Event Applies to Occurs when Handler
MouseDown Documents, buttons, User depresses onMouseDown
links a mouse button
MouseUp Documents, buttons, User releases a onMouseUp
links mouse button
Click Buttons, radio User clicks a onClick
buttons, checkboxes, form element or
submit buttons, reset link
buttons, links
0
Events and event handlers IV
Event Applies to Occurs when Handler
MouseOver Links User moves onMouseOver
cursor over a
link
MouseOut Areas, links User moves onMouseOut
cursor out of an
image map or
link
Select Text fields, text User selects form onSelect
areas element’s input
field
0
Events and event handlers V
Event Applies to Occurs when Handler
x
Move Windows User or script moves a onMove
window
Resize Windows User or script resizes a onResize
window
DragDrop Windows User drops an object onDragDrop
onto the browser
window
0
Events and event handlers VI
Event Applies to Occurs when Handler
Focus Windows and all form User gives onFocus
elements element input
focus
Blur Windows and all form User moves focus onBlur
elements to some other
element
Reset Forms User clicks a onReset
Reset button
Submit Forms User clicks a onSubmit
Submit button
0
Back to the DOM
● You can attach event handlers to HTML elements with very little
knowledge of the DOM
● However, to change what is displayed on the page requires
knowledge of how to refer to the various elements
● The basic DOM is a W3C standard and is consistent across
various browsers
● More complex features are browser-dependent
● The highest level element (for the current page) is window, and
everything else descends from that
0
The DOM
hierarchy
Source:
http://sislands.com/coin70/week1/dom.htm
0
Fields of window, I
● window
● The current window (not usually needed).
● self
● Same as window.
● parent
● If in a frame, the immediately enclosing window.
● top
● If in a frame, the outermost enclosing window.
● frames[ ]
● An array of frames (if any) within the current window. Frames are
themselves windows.
● length
● The number of frames contained in this window.
0
Fields of window, II
● document
● The HTML document being displayed in this window.
● location
● The URL of the document being displayed in this window. If you set this
property to a new URL, that URL will be loaded into this window. Calling
location.reload() will refresh the window.
● navigator
● A reference to the Navigator (browser) object. Some properties of
Navigator are:
● appName -- the name of the browser, such as "Netscape"
● platform -- the computer running the browser, such as "Win32"
● status
● A read/write string displayed in the status area of the browser window. Can
be changed with a simple assignment statement.
0
Methods of window, I
● alert(string)
● Displays an alert dialog box containing the string and an OK
button.
● confirm(string)
● Displays a confirmation box containing the string along with
Cancel and OK buttons. Returns true if OK is pressed, false if
Cancel is pressed.
● prompt(string)
● Displays a confirmation box containing the string, a text field,
and Cancel and OK buttons. Returns the string entered by the
user if OK is pressed, null if Cancel is pressed.
0
Methods of window, II
● open(URL)
● Opens a new window containing the document specified by
the URL.
● close()
● Closes the given window (which should be a top-level
window, not a frame).
0
Fields of document, I
● You must prefix these fields with document.
● anchors[ ]
● An array of Anchor objects (objects representing
<a name=...> tags)
● applets[ ]
● An array of Applet objects
● The properties are the public fields defined in the applet
● The methods are the public methods of the applet
● Cautions:
● You must supply values of the correct types for the fields and
method parameters
● Changes and method calls are done in a separate Thread
0
Fields of document, II
● forms[ ]
● An array of Form elements
● If the document contains only one form, it is forms[0]
● elements[ ] : field of form which is an array of form elements
● images[ ]
● An array of Image objects
● To change the image, assign a new URL to the src property
● links[ ]
● An array of Link objects
● A link has several properties, including href, which holds the
complete URL
0
Fields of document, III
● bgColor
● The background color of the document
● May be changed at any time
● title
● A read-only string containing the title of the document
● URL
● A read-only string containing the URL of the document