JavaScript objects and events
predefined classes & objects
String, Array, Date, document, navigator
user-defined classes
encapsulation, but no data hiding
event-driven programming
onLoad/onUnload
onClick, onMouseOver, onMouseOut
Classes vs. objects
in programming terminology:
a class is a definition of a new type (a.k.a. ADT)
encapsulates both data (a.k.a. properties) and functions (a.k.a. methods)
usually, can hide data & force the use of functions
an object is an instance of a class
e.g., in C++, the String class encapsulates
• a sequence of characters and
• various methods (e.g., length, [], substring, find, …)
String str = "foobar"; // str is a String object
cout << str.length(); // applies length method to str object
JavaScript predefined classes
we have already seen 2 predefined JavaScript classes
String: encapsulates a sequence of characters, indexed
properties include: length
methods include: charAt, substring, toUpperCase,
indexOf
Array: encapsulates a sequence of elements, indexed
properties include: length
methods include: [], reverse, sort, slice, pop, push
to create and allocate an object in JavaScript, use new
numbers = new Array(4); // calls Array constructor
firstName = new String("Dave"); // calls String constructor
for both String and Array, can assign constant values directly, hide call to new
numbers = [1, 2, 3, 4]; // creates and initializes
firstName = "Dave"; // same as above, but cleaner
Date class
the Date class can be used to access the date and time
constructors include:
today = new Date(); // sets to current date & time
newYear = new Date(2001,0,1); //sets to Jan 1, 2001 12:00AM
methods include:
newYear.getYear() can access individual components of a date
newYear.getMonth()
newYear.getDay()
newYear.getHours()
newYear.getMinutes()
newYear.getSeconds()
newYear.getMilliseconds()
newYear.toString() can convert date to printable String
Date example
<html>
<head>
<title>Time page</title>
</head> Here, set to the current date and
time using the default
<body>
Time when page was loaded: constructor
<script language="JavaScript">
now = new Date();
toString displays the full date
document.write(now.toString() + "<br><br>"); using month and day names
document.write(now.getHours() + ":" + using the get methods, can
now.getMinutes() + ":" +
now.getSeconds()); display desired components of
</script> the date/time
</body>
</html>
Date example (cont.)
<html>
<head>
<title>Time page</title>
</head>
<body> suppose we don’t like military time
Time when page was loaded:
<script language="JavaScript">
now = new Date();
instead of 0:15:22
we want 12:15:22 AM
time = "AM";
hours = now.getHours();
if (hours > 12) { we must perform the conversions
hours -= 12;
time = "PM" • need a variable for "AM" or "PM"
}
else if (hours == 0) {
hours = 12; • need to adjust hours past noon
}
document.write(hours + ":" +
• need to handle 12 AM special
now.getMinutes() + ":" +
now.getSeconds() + " " +
time);
</script>
</body>
</html>
Another example
<html>
<head>
<title>Time page</title>
</head>
<body> you can add and subtract Dates:
Time in the new millenium:
<script language="JavaScript">
the result is a number of
now = new Date(); milliseconds
newYear = new Date(2001,0,1);
here, determine the number of
secs = Math.round((now-newYear)/1000);
seconds since New Year's day
days = Math.floor(secs / 86400);
secs -= days*86400; divide into number of days, hours,
hours = Math.floor(secs / 3600);
secs -= hours*3600;
minutes and seconds
minutes = Math.floor(secs / 60);
secs -= minutes*60
document.write(days + " days, " +
hours + " hours, " +
possible improvements?
minutes + " minutes, and " +
secs + " seconds.");
</script>
</body>
</html>
document object
Both IE and Netscape allow you to access information about an
HTML document using the document object (Note: not a class!)
<html>
document.write(…)
<head>
<title>Documentation page</title> method that displays text
</head> in the page
<body>
<table width="100%">
<tr> document.URL
<td><small><i> property that gives the
<script language="JavaScript"> location of the HTML
document.write(document.URL); document
</script>
</i></small></td>
<td align="right"><small><I>
<script language="JavaScript"> document.lastModified
document.write(document.lastModified); property that gives the date
</script> & time the HTML
</i></small></td> document was saved
</tr>
</table>
</body>
</html>
navigator object
can access information about the browser being used to access the
Web page using the navigator object (Again: not a class!)
navigator.appName property gives the browser name, e.g.,
"Netscape"
"Microsoft Internet Explorer"
navigator.appVersion property gives the browser version, e.g.,
"4.0 (compatible; MSIE 5.0; Windows 98; DigExt) )
navigator.plugins property gives an array of all of the installed plug-ins
navigator example
can have a separate style <html>
sheet file for each browser <head>
<title>Dynamic Style Page</title>
use navigator.appName to
find out which browser used <script language="JavaScript">
if (navigator.appName == "Netscape") {
document.write('<link rel=stylesheet '+
dynamically write the LINK 'type="text/css" href="Netscape.css">');
tag with corresponding HREF }
else {
document.write('<link rel=stylesheet ' +
<!-- MSIE.css --> 'type="text/css" href="MSIE.css">');
}
a {text-decoration:none; </script>
font-size:larger; </head>
color:red;
font-family:Arial} <body>
a:hover {color:blue} Here is some text with a
<a href="javascript:alert('GO AWAY')">link</a>.
</body>
<!-- Netscape.css --> </html>
a {font-family:Arial;
color:white;
background-color:red}
User-defined classes
can define new classes, but the notation is awkward
simply define a function that serves as a constructor
specify data fields & methods using this
no data hiding: can't protect data or methods
// Die class definition
//////////////////////////////////////////// define Die function
function Die(sides) (i.e., constructor)
{
this.numSides = sides; initialize data fields in
this.numRolls = 0;
the function, preceded
this.Roll = Roll;
} with this
function Roll() similarly, assign method
{
this.numRolls++; to separately defined
return Math.floor(Math.random()*this.numSides) + 1; function (which uses
} this to access data)
<html>
<head> Class example
<title>Dice page</title>
<script language="JavaScript"
src="Die.js"> create a Die object using
</script> new (similar to String and
</head> Array)
<body>
<script language="JavaScript"> here, the argument to Die
die6 = new Die(6); initializes numSides for
die8 = new Die(8); that particular object
roll6 = -1; // dummy value to start loop
roll8 = -2; // dummy value to start loop each Die object has its own
while (roll6 != roll8) { properties (numSides &
roll6 = die6.Roll();
roll8 = die8.Roll();
numRolls)
document.write("6-sided: " + roll6 + Roll(), when called on a
" " + particular Die, accesses its
"8-sided: " + roll8 + "<br>");
} numSides property and
updates its NumRolls
document.write("<p>Number of rolls: " +
die6.numRolls);
</script>
</body>
</html>
Event-driven programs
in C++, programs are serially executed
start with main function, execute sequentially from first statement
may loop or skip sections of code, but the program proceeds step-by-step
the programmer specifies the sequence in which execution
occurs (with some variability due to input values)
there is a beginning and an end to program execution
computation within a Web page is rarely serial
instead, the page reacts to events such as mouse clicks, buttons, …
much of JavaScript's utility is in specifying actions that are to occur in the
page as a result of some event
the programmer may have little or no control over when code will (if
ever) be executed, e.g., code that reacts to a button click
there is no set sequence, the page waits for events and reacts
OnLoad & OnUnload
<html>
<head>
<title>Hello/Goodbye page</title>
the simplest events are
when the page is loaded
<script language="JavaScript">
function Hello() or unloaded
{
userName=prompt("Welcome to my page. " + the ONLOAD attribute of
"What is your name?",""); the BODY tag specifies
} JavaScript code that is
automatically executed
function Goodbye() when the page is loaded
{
userName=alert("So long, " + userName + the ONUNLOAD attribute
" come back real soon."); similarly specifies
} JavaScript code that is
</script> automatically executed
when the browser leaves
</head> the page
<body onLoad="Hello();" onUnload="Goodbye();">
Whatever text appears in the page.
</body>
</html>
<html>
<head> User-driven events
<title>Anchor events</title>
<script language="JavaScript"
src="http://www.creighton.edu/~csc551/ can add event-handling to
JavaScript/random.js">
</script> anchors and images
<script language="JavaScript"> ONCLICK attribute
function GetNumber(maxNum)
{ specifies what is to occur
var number = randomInt(1, maxNum); if the user clicks on the
alert("The lucky number for today is " + element
number)
} ONMOUSEOVER
</script> attribute specifies what is
</head>
to occur when the mouse
<body> passes over the element
For today's lucky number,
<a href="#" onClick="GetNumber(100);"> ONMOUSEOUT attribute
click here</a> specifies what is to occur
when the mouse moves off
<p> the element
Or better yet,
<a href="javascript:GetNumber(100);">
try here</a>
</body>
</html>
Image events
<html> can use an image to
simulate a link
<head>
<title>Title for Page</title> can change the image
</head> when the mouse moves
over or out
<body>
<a href="javascript:alert('Do NOT click on me!');"> can perform an act (e.g.,
<img src="reed.gif" alt="Dave Reed"></a> open a new window,
change the file in a frame)
<p><br> when clicked
<img src="click1.gif" when used in a menu,
onmouseover="this.src='click2.gif'" clickable images have
onmouseout="this.src='click1.gif'" some advantages over
onclick="alert('Thank you')"> links
</body>
</html>