Lecture 7
Lecture 7
Lecture 7
Introduction to JavaScript
▪ JavaScript
➢ data types & expressions
➢ control statements
➢ functions & libraries
➢ strings & arrays
➢ Date, document, navigator, user-defined classes
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
Scripts vs. programs
a scripting language is a simple, interpreted programming language
▪ scripts are embedded as plain text, interpreted by application
<html>
<!-- js01.html --> document.write displays text in page
conditional execution:
counter-driven looping:
<html>
<!-- js08.html --> Note: prompt always returns a
string
<head>
<title>Prompting for numbers</title>
</head> if the user enters the number 12
at the prompt, the string "12" is
<body>
<script type="text/javascript"> returned
num1 = prompt("Enter the first number", "1");
num1 = parseFloat(num1); recall: + applied to strings gives
concatenation
num2 = prompt("Enter the second number", "2");
num2 = parseFloat(num2);
if numbers are to be read using
document.write("The sum of the numbers is " + prompt, they must be explicitly
(num1 + num2));
</script> converted to numbers using
</body> parseFloat
</html>
function isPrime(n)
// Assumes: n > 0
// Returns: true if n is prime, else false can limit variable scope
{
if (n < 2) {
return false;
if the first use of a variable is preceded
} 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;
}
}
Function example
<html>
<!-- js09.html -->
function
<head>
<title>Prime Tester</title>
definitions go in
the HEAD
<script type="text/javascript">
function isPrime(n)
// Assumes: n > 0 HEAD is loaded first,
// Returns: true if n is prime
{
so the function is
// CODE AS SHOWN ON PREVIOUS SLIDE defined before code
} in the BODY is
</script> executed
</head>
<body>
<script type="text/javascript">
testNum = prompt("Enter a positive integer", "7");
testNum = parseFloat(testNum);
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> view page in
</html> browser
<html>
<!-- js10.html --> 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);
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.csuhayward.edu/~bhecker/cs3520/JavaScript/random.js">
</script>
Library example
<html>
<!-- js11.html -->
<head>
<title> Random Dice Rolls Revisited</title>
<script type="text/javascript"
src="http://www.msc.csuhayward.edu/bhecker/CS-
3520/Examples/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.mcs.csuhayward.edu/"+
"~bhecker/CS-3520/Examples/JavaScript/die" +
roll1 + ".gif' />");
document.write(" ");
document.write("<img src='http://www.mcs.csuhayward.edu/"+
"~bhecker/CS-3520/Examples/JavaScript/die" +
roll2 + ".gif' />");
</script>
</div>
</body>
</html> view page in browser
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 traverse the string,
// Returns: true if str is a palindrome, else false
{ comparing characters from
str = str.toUpperCase(); front to back
for(var i = 0; i < Math.floor(str.length/2); i++) {
if (str.charAt(i) != str.charAt(str.length-i-1)) { should be case-insensitive,
return false; so make all letters
}
} uppercase before testing
return true;
}
String example (pt. 2)
function Strip(str)
// Assumes: str is a string better yet, we would like
// Returns: str with all but capital letters removed
{ to be able to test
var copy = ""; phrases
for (var i = 0; i < str.length; i++) {
if (str.charAt(i) >= "A" && str.charAt(i) <= "Z") {
copy += str.charAt(i); Madam, I'm Adam.
}
} A man, a plan, a canal:
return copy;
} Panama!
function IsPalindrome(str)
// Assumes: str is a string
must strip non-letters out of the
// Returns: true if str is a palindrome, else false phrase, then test as before
{
str = Strip(str.toUpperCase()); to handle phrases, must be
for(var i = 0; i < Math.floor(str.length/2); i++) { able to strip out non-letters
if (str.charAt(i) != str.charAt(str.length-i-1)) {
return false;
}
}
return true;
}
<html>
<!-- js12.html -->
<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
</body> browser
</html>
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; simulate die rolls and
dieSides = 6;
verify even distribution
rolls = new Array(dieSides+1);
for (i = 1; i < rolls.length; i++) { keep an array of counters:
rolls[i] = 0;
}
initialize each count to 0
for(i = 1; i <= numRolls; i++) {
rolls[RandomInt(1, dieSides)]++; each time you roll X,
} increment rolls[X]
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
today = new Date(); // sets to current date & time
▪ 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>
navigator object
navigator.appName <html>
<!-- js17.html -->
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
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
// Die.js
// define Die function (i.e.,
// Die class definition
//////////////////////////////////////////// constructor)