CSC 551: Web Programming Spring 2004: Client-Side Programming With Javascript
CSC 551: Web Programming Spring 2004: Client-Side Programming With Javascript
Spring 2004
JavaScript
data types & expressions
control statements
functions & libraries
strings & arrays
Date, document, navigator, user-defined classes
1
Client-side programming
recall: HTML is good for developing static pages
can specify text/image layout, presentation, links, …
Web page looks the same each time it is accessed
client-side programming
programs are written in a separate programming language
e.g., JavaScript, JScript, VBScript
programs are embedded in the HTML of a Web page, with tags to identify the
program component
e.g., <script type="text/javascript"> … </script>
the browser executes the program as it loads the page, integrating the dynamic
output of the program with the static content of HTML
2
Scripts vs. programs
a scripting language is a simple, interpreted programming language
scripts are embedded as plain text, interpreted by application
<html>
<!-- Dave Reed js01.html 2/01/04 --> document.write displays text in page
foldCount = 0;
while (thickness < distanceToSun) { PUZZLE: Suppose you took a piece
thickness *= 2; of paper and folded it in half, then in
foldCount++;
}
half again, and so on.
document.write("Number of folds = " +
foldCount); How many folds before the thickness
</script>
</body> of the paper reaches from the earth to
</html> the sun?
view page in browser
7
JavaScript Math routines
<html> the Math object
<!-- Dave Reed js04.html 2/01/04 -->
contains functions
<head> and constants
<title>Random Dice Rolls</title>
</head>
Math.sqrt
<body> Math.pow
<div style="text-align:center"> Math.abs
<script type="text/javascript"> Math.max
roll1 = Math.floor(Math.random()*6) + 1; Math.min
roll2 = Math.floor(Math.random()*6) + 1; Math.floor
Math.ceil
document.write("<img src='http://www.creighton.edu/"+
Math.round
"~davereed/csc551/Images/die" +
roll1 + ".gif' />");
document.write(" "); Math.PI
document.write("<img src='http://www.creighton.edu/"+ Math.E
"~davereed/csc551/Images/die" +
roll2 + ".gif' />"); Math.random
</script>
</div>
function returns
</body> number in [0..1)
</html>
view page in browser 8
Interactive pages using prompt crude user interaction can
take place using prompt
<html>
<!-- Dave Reed js05.html 2/01/04 -->
1st argument: the prompt
<head> message that appears in the
<title>Interactive page</title> dialog box
</head>
function isPrime(n)
// Assumes: n > 0
// Returns: true if n is prime, else false can limit variable scope
{
if (n < 2) { if the first use of a variable is preceded
return false;
} with var, then that variable is local to
else if (n == 2) { the function
return true;
}
else {
for modularity, should make all
for (var i = 2; i <= Math.sqrt(n); i++) { variables in a function local
if (n % i == 0) {
return false;
}
}
return true;
}
} 10
Function example
<html>
<!-- Dave Reed js06.html 2/01/04 -->
function
<head>
<title>Prime Tester</title>
definitions go in
the HEAD
<script type="text/javascript">
function isPrime(n)
// Assumes: n > 0 HEAD is loaded
// Returns: true if n is prime
first, so the function
{
// CODE AS SHOWN ON PREVIOUS SLIDE is defined before
} code in the BODY is
</script> executed
</head>
<body>
<script type="text/javascript">
testNum = parseFloat(prompt("Enter a positive integer", "7"));
if (isPrime(testNum)) {
document.write(testNum + " <b>is</b> a prime number.");
}
else {
document.write(testNum + " <b>is not</b> a prime number.");
}
</script>
</body>
</html>
view page in brows
er 11
<html>
<!-- Dave Reed js07.html 2/01/04 --> Another
<head>
<title> Random Dice Rolls Revisited</title> example
<script type="text/javascript">
function RandomInt(low, high)
// Assumes: low <= high
// Returns: random integer in range [low..high]
{
return Math.floor(Math.random()*(high-low+1)) + low;
recall the dynamic dice
} page
</script>
</head>
could define a function for
<body> generating random
<div align="center">
<script type="text/javascript"> numbers in a range, then
roll1 = RandomInt(1, 6); use whenever needed
roll2 = RandomInt(1, 6);
document.write("<img src='http://www.creighton.edu/"+
easier to remember,
"~davereed/csc551/Images/die" + promotes reuse
roll1 + ".gif' />");
document.write(" ");
document.write("<img src='http://www.creighton.edu/"+
"~davereed/csc551/Images/die" +
roll2 + ".gif' />"); view page in br
</script> owser
</div>
</body>
12
</html>
JavaScript libraries
better still: if you define functions that may be useful to many pages, store in a
separate library file and load the library when needed
Note: as with external style sheets, no tags in the JavaScript library file
load a library using the SRC attribute in the SCRIPT tag (nothing between the tags)
<script type="text/javascript"
src="http://www.creighton.edu/~davereed/csc551/JavaScript/random.js">
</script>
13
Library example
<html>
<!-- Dave Reed js08.html 2/01/04 -->
<head>
<title> Random Dice Rolls Revisited</title>
<script type="text/javascript"
src="http://www.creighton.edu/~davereed/csc551/JavaScript/random.js">
</script>
</head>
<body>
<div align="center">
<script type="text/javascript">
roll1 = RandomInt(1, 6);
roll2 = RandomInt(1, 6);
document.write("<img src='http://www.creighton.edu/"+
"~davereed/csc551/Images/die" +
roll1 + ".gif' />");
document.write(" ");
document.write("<img src='http://www.creighton.edu/"+
"~davereed/csc551/Images/die" +
roll2 + ".gif' />");
</script>
</div>
</body>
</html>
view page in browser 14
JavaScript Strings
a class defines a new type (formally, Abstract Data Type)
encapsulates data (properties) and operations on that data (methods)
to create a string, assign using new or just make a direct assignment (new is implicit)
word = new String("foo"); word = "foo";
function IsPalindrome(str)
// Assumes: str is a string must strip non-letters out of the
// Returns: true if str is a palindrome, else false word or phrase
{
str = Strip(str.toUpperCase());
make all chars uppercasein
for(var i = 0; i < Math.floor(str.length/2); i++) { order to be case-insensitive
if (str.charAt(i) != str.charAt(str.length-i-1)) {
return false;
} finally, traverse and compare
} chars from each end
return true;
}
16
<html>
<!-- Dave Reed js09.html 2/01/04 -->
<head>
<title>Palindrome Checker</title>
<script type="text/javascript">
function Strip(str)
{
// CODE AS SHOWN ON PREVIOUS SLIDE
}
function IsPalindrome(str)
{
// CODE AS SHOWN ON PREVIOUS SLIDE
}
</script>
</head>
<body>
<script type="text/javascript">
text = prompt("Enter a word or phrase", "Madam, I'm Adam");
if (IsPalindrome(text)) {
document.write("'" + text + "' <b>is</b> a palindrome.");
}
else {
document.write("'" + text + "' <b>is not</b> a palindrome.");
}
</script> view page in br
</body> owser
</html> 17
JavaScript arrays
arrays store a sequence of items, accessible via an index
since JavaScript is loosely typed, elements do not have to be the same type
to create an array, allocate space using new (or can assign directly)
items = new Array(10); // allocates space for 10 items
<body>
<script type="text/javascript"> suppose we want to
numRolls = 60000;
dieSides = 6; simulate die rolls and
verify even distribution
rolls = new Array(dieSides+1);
for (i = 1; i < rolls.length; i++) {
rolls[i] = 0; keep an array of counters:
}
initialize each count to 0
for(i = 1; i <= numRolls; i++) {
rolls[RandomInt(1, dieSides)]++; each time you roll X,
}
increment rolls[X]
for (i = 1; i < rolls.length; i++) {
document.write("Number of " + i + "'s = " + display each counter
rolls[i] + "<br />");
}
</script>
</body> view page in browser
</html> 19
Date class
String & Array are the most commonly used classes in JavaScript
other, special purpose classes & objects also exist
the Date class can be used to access the date and time
to create a Date object, use new & supply year/month/day/… as desired
methods include:
<body>
<table width="100%"> document.URL
<tr> property that gives the
<td><small><i> location of the HTML
<script type="text/javascript"> document
document.write(document.URL);
</script>
</i></small></td>
<td align="right"><small><I> document.lastModified
<script type="text/javascript"> property that gives the date &
document.write(document.lastModified); time the HTML document was
</script> saved
</i></small></td>
</tr>
</table>
</body> view page in browser
</html> 23
navigator object
navigator.appName <html>
<!-- Dave Reed js14.html 2/01/04 -->
property that gives the browser
name <head>
<title>Dynamic Style Page</title>
navigator.appVersion
<script type="text/javascript">
property that gives the browser if (navigator.appName == "Netscape") {
version document.write('<link rel=stylesheet '+
'type="text/css" href="Netscape.css">');
}
<!-- MSIE.css --> else {
document.write('<link rel=stylesheet ' +
a {text-decoration:none; 'type="text/css" href="MSIE.css">');
font-size:larger; }
color:red; </script>
font-family:Arial} </head>
a:hover {color:blue}
<body>
<!-- Netscape.css --> Here is some text with a
<a href="javascript:alert('GO AWAY')">link</a>.
a {font-family:Arial; </body>
color:white; </html>
background-color:red}
view page in browser
24
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