Lec4 JavaScript
Lec4 JavaScript
JavaScript
scripts vs. programs
JavaScript vs. JScript vs. VBScript
common tasks for client-side scripts
JavaScript
data types & expressions
control statements
functions & libraries
strings & arrays
Date, document, navigator, user-
defined classes
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 (or scripting) language
e.g., JavaScript, JScript, VBScript
programs are embedded in the HTML of a Web page, with (HTML) tags
to identify the program component
e.g., <script type="text/javascript"> … </script>
<script type="text/javascript"
src="random.js">
</script>
<html>
<!–- CS443 js08.html 11.10.2011 -->
<head>
<title> Random Dice Rolls Revisited</title>
<script type="text/javascript"
src="random.js">
</script>
</head>
<body>
<div style="text-align: center">
<script type="text/javascript">
roll1 = randomInt(1, 6);
roll2 = randomInt(1, 6);
document.write("<img src='http://www.csc.liv.ac.uk/"+
"~martin/teaching/CS443/Images/die" +
roll1 + ".gif'/>");
document.write(" ");
document.write("<img src='http://www.csc.liv.ac.uk/"+
"~martin/teaching/CS443/Images/die" +
roll2 + ".gif'/>");
</script>
</div>
</body>
</html>
an object defines a new type (formally, Abstract Data Type)
encapsulates data (properties) and operations on that data (methods)
a String object encapsulates a sequence of characters, enclosed in quotes
properties include
• length : stores the number of characters in the string
methods include
• charAt(index): returns the character stored at the given
index (as in C++/Java, indices start at 0)
• substring(start, end) : returns the part of the string
between the start (inclusive) and end (exclusive) indices
• toUpperCase() : returns copy of string with
uppercase letters
• toLowerCase()
lowercase : returns copy of string with
letters
to create a string, assign using new or (in this case) just make a direct
assignment (new is implicit)
word = new String("foo"); word = "foo";
properties/methods are called exactly as in C++/Java
• word.length word.charAt(0)
function strip(str)
// Assumes: str is a string suppose we want to
// Returns: str with all but letters removed test whether a word or
{
var copy = ""; phrase is a palindrome
for (var i = 0; i < str.length; i++) {
if ((str.charAt(i) >= "A" && str.charAt(i) <= "Z")
|| noon Radar
(str.charAt(i) >= "a" && str.charAt(i) <= "z")) Madam, I'm
{
Adam.
copy += str.charAt(i);
} A man, a plan, a
} canal: Panama!
return copy;
}
var q = [1,2,3,4,5,6,7,8,9,10];
item = q.shift(); // item is now equal to 1, remaining
// elements of q move down one position
// in the array, e.g. q[0] equals 2
q.unshift(125); // q is now the array [125,2,3,4,5,6,7,8,9,10]
q.push(244); // q = [125,2,3,4,5,6,7,8,9,10,244]
String & Array are the most commonly used objects in JavaScript
other, special purpose objects also exist
the Date object 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
newYear = new Date(2002,0,1); //sets to Jan 1, 2002 12:00AM
methods include:
newYear.getFullYear() can access individual components of a date
newYear.getMonth() number (0, 11)
newYear.getDay() number (1, 31)
newYear.getHours() number (0, 23)
newYear.getMinutes() number (0, 59)
newYear.getSeconds() number (0, 59)
newYear.getMilliseconds() number (0, 999)
DATE EXAMPLE
<html>
<!–- CS443 js11.html 16.08.2006 -->
<head>
<title>Time page</title>
</head>
<body> by default, a date will be
Time when page was loaded:
<script type="text/javascript">
displayed in full, e.g.,
now = new Date(); Sun Feb 03 22:55:20 GMT-0600
document.write("<p>" + now + "</p>"); (Central Standard Time) 2002
time = "AM";
hours = now.getHours();
if (hours > 12) {
hours -= 12; can pull out portions of the date
time = "PM" using the methods and display
}
else if (hours == 0) {
as desired
hours = 12;
}
here, determine if "AM" or "PM"
document.write("<p>" + hours + ":" + and adjust so hour between 1-12
now.getMinutes() + ":" + 10:55:20 PM
now.getSeconds() + " " +
time + "</p>");
</script>
</body>
</html>
ANOTHER EXAMPLE
<html>
<!–- CS443 js12.html 12.10.2012 -->
<head>
<title>Time page</title>
</head> you can add and subtract
<body> Dates:
<p>Elapsed time in this year:
<script type="text/javascript">
the result is a number of
now = new Date(); milliseconds
newYear = new Date(2012,0,1);
secs = Math.round((now-newYear)/1000); here, determine the
days = Math.floor(secs / 86400); number of seconds since
secs -= days*86400;
hours = Math.floor(secs / 3600); New Year's day (note:
secs -= hours*3600; January is month 0)
minutes = Math.floor(secs / 60);
secs -= minutes*60 divide into number of days,
document.write(days + " days, " + hours, minutes and seconds
hours + " hours, " +
minutes + " minutes, and " +
secs + " seconds.");
</script>
</p>
</body>
</html>
Internet Explorer, Firefox, Opera, etc. allow you to access
information about an HTML document using the document object
<html>
<!–- CS443 js13.html 2.10.2012 -->
<head>
document.write(…)
<title>Documentation page</title> method that displays text in
</head> the page
<body>
<table width="100%">
<tr>
document.URL
<td><i> property that gives the
<script type="text/javascript">
document.write(document.URL); location of the HTML
</script> document
</i></td>
<td style="text-align: right;"><i> document.lastModified
<script type="text/javascript">
document.write(document.lastModified); property that gives the date
</script>
</i></td>
& time the HTML
</tr> document was last
</table>
</body>
changed
</html>
<html>
<!–- CS443 js14.html 16.08.2006 -->
navigator.appName
<head>
property that gives <title>Dynamic Style Page</title>
the browser name
<script type="text/javascript">
navigator.appVer if (navigator.appName ==
sion property that "Netscape") {
gives the browser document.write('<link
version rel=stylesheet '+
'type="text/css"
<!-- MSIE.css --> href="Netscape.css">');
}
<!-- Netscape.css else {
a {text-
--> document.write('<link
decoration:none;
rel=stylesheet ' +
font- 'type="text/css"
a {font- size:larger;
family:Arial; href="MSIE.css">');
color:red;
color:white; }
font-
background- </script>
family:Arial} </head>
color:red} a:hover
{color:blue}
<body>
Here is some text with a
<a href="javascript:alert('GO
AWAY')">link</a>.
</body>
</html>
•In order to use an HTML validator, and not get error messages from
the JavaScript portions, you must “mark” the JavaScipt sections in a
particular manner. Otherwise the validator will try to interpret the
script as HTML code.
•To do this, you can use a markup like the following in your inline code
(this isn’t necessary for scripts stored in external files).
<script type=“text/javascript”>
// <![CDATA[
// ]]>
</script>
•Since the (new) XHTML standard is written as an XML application,
validators such as the one from the W3C are actually attempting to
check an XML document for the correct structure.
•The two tags <![CDATA[ and ]]> together form an XML directive,
meaning to interpret the data between them as literal (non-parsed)
“character data”. An XML validator will effectively ignore the data
between these two tags, meaning that any symbols that would result
in an invalid document structure are ignored and do not result in an
error message from the validator.