Lec3-1 - Javascript
Lec3-1 - Javascript
Lec3-1 - Javascript
2020-2
JavaScript
Content
Client-side programming with 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
1
Client-Side Programming
• 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>
§ the browser executes the program as it loads the page, integrating the dynamic output of
the program with the static content of HTML
§ could also allow the user (client) to input information and process it, might be used to
validate input before it’s submitted to a remote server
JavaScript 1.5 & JScript 5.0 cores both conform to ECMAScript standard
2
Common Scripting Tasks
• adding dynamic features to Web pages
§ validation of form data (probably the most commonly used application)
§ image rollovers
§ time-sensitive or random page elements
§ handling cookies
JavaScript
• JavaScript code can be embedded in a Web page using <script> tags
§ the output of JavaScript code is displayed as if directly entered in HTML
<head>
text to be displayed can include HTML
<title>JavaScript Page</title> tags
</head>
the tags are interpreted by the browser
<body> when the text is displayed
<script type="text/javascript">
// silly code to demonstrate output
3
JavaScript Data Types & Variables
• JavaScript has only three primitive data types
String : "foo" 'how do you do?' "I said 'hi'." ""
Number: 12 3.14159 1.5E6
Boolean : true false *Find info on Null, Undefined
4
JavaScript Math Routines
<html> the built-in Math
<!–- CS443 js04.html 08.10.10 -->
object contains
<head> functions and
<title>Random Dice Rolls</title> constants
</head>
<body> Math.sqrt
<div style="text-align:center"> Math.pow
<script type="text/javascript"> Math.abs
var roll1 = Math.floor(Math.random()*6) + 1; Math.max
var roll2 = Math.floor(Math.random()*6) + 1; Math.min
document.write("<img src='http://www.csc.liv.ac.uk/"+ Math.floor
"~martin/teaching/CS443/Images/die" + Math.ceil
roll1 + ".gif‘ alt=‘dice showing ‘ + roll1 />"); Math.round
document.write(" ");
document.write("<img src='http://www.csc.liv.ac.uk/"+ Math.PI
"~martin/teaching/CS443/Images/die" + Math.E
roll2 + ".gif‘ alt=‘dice showing ‘ + roll2 />");
</script>
</div>
Math.random
</body> function returns a real
</html>
number in [0..1)
view page
5
User-Defined Functions
• function definitions are similar to C++/Java, except:
§ no return type for the function (since variables are loosely typed)
§ no variable typing for parameters (since variables are loosely typed)
§ by-value parameter passing only (parameter gets copy of argument)
function isPrime(n)
// Assumes: n > 0 Can limit variable scope to the
// Returns: true if n is prime, else false
{
function.
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) {
return true;
the function
}
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;
}
}
11
Function Example
<html>
<!–- CS443 js06.html 16.08.2006 -->
12
6
<html>
<!–- CS443 js07.html 11.10.2011 --> 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>
<div style="text-align: center">
generating random
<script type="text/javascript"> numbers in a range, then
roll1 = randomInt(1, 6); use whenever needed
roll2 = randomInt(1, 6);
13
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
load a library using the SRC attribute in the SCRIPT tag (put nothing between the beginning
and ending tags)
<script type="text/javascript"
src="random.js">
</script>
14
7
Library Example
<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> view page
</html>
15
JavaScript Objects
• an object 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 (in this case) just make a direct assignment (new is implicit)
word = new String("foo"); word = "foo";
16
8
String example: Palindromes
function strip(str)
// Assumes: str is a string
suppose we want to
// Returns: str with all but letters removed test whether a word
{
var copy = ""; or phrase is a
for (var i = 0; i < str.length; i++) {
if ((str.charAt(i) >= "A" && str.charAt(i) <= "Z") ||
palindrome
(str.charAt(i) >= "a" && str.charAt(i) <= "z")) {
copy += str.charAt(i);
} noon Radar
} Madam, I'm Adam.
return copy; A man, a plan, a canal:
}
Panama!
function isPalindrome(str)
// Assumes: str is a string
// Returns: true if str is a palindrome, else false must strip non-letters out of the
{
str = strip(str.toUpperCase()); word or phrase
17
<html>
<!–- CS443 js09.html 11.10.2011 -->
<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>
</body> view page
</html>
18
9
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
19
Array Example
<html>
suppose we want to
<!–- CS443 js10.html 11.10.2011 -->
<head> simulate dice rolls and
<title>Dice Statistics</title> verify even distribution
<script type="text/javascript"
src="http://www.csc.liv.ac.uk/~martin/teaching/CS443/JS/ran
dom.js"> keep an array of counters:
</script>
</head>
<body> initialize each count to 0
<script type="text/javascript">
numRolls = 60000; each time you roll X,
diceSides = 6; increment rolls[X]
20
10
Arrays (cont.)
• Arrays have predefined methods that allow them to be used as stacks,
queues, or other common programming data structures.
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]
21
Date Object
• 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
§ methods include:
22
11
<html>
Date Example
<!–- CS443 js11.html 16.08.2006 -->
<head>
<title>Time page</title>
</head>
by default, a date will be displayed in
<body> full, e.g.,
Time when page was loaded:
<script type="text/javascript"> Sun Feb 03 22:55:20 GMT-0600
now = new Date(); (Central Standard Time) 2002
23
Another Example
<html>
<!–- CS443 js12.html 12.10.2012 -->
<head>
<title>Time page</title>
</head>
you can add and subtract Dates:
<body> the result is a number of
<p>Elapsed time in this year:
milliseconds
<script type="text/javascript">
now = new Date();
newYear = new Date(2012,0,1); here, determine the number of
seconds since New Year's day
secs = Math.round((now-newYear)/1000);
(note: January is month 0)
days = Math.floor(secs / 86400);
secs -= days*86400; divide into number of days, hours,
hours = Math.floor(secs / 3600); minutes and seconds
secs -= hours*3600;
minutes = Math.floor(secs / 60);
secs -= minutes*60
24
12
Document Object
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 -->
document.write(…)
<head>
<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"> location of the HTML
document.write(document.URL); document
</script>
</i></td>
<td style="text-align: right;"><i> document.lastModified
<script type="text/javascript">
document.write(document.lastModified); property that gives the date &
</script>
time the HTML document was
</i></td> last changed
</tr>
</table>
</body>
</html> view page
25
User-Defined Objects
• can define new objects, but the notation can be somewhat awkward
§ simply define a function that serves as a constructor
§ specify data fields & methods using this
26
13
<html>
<!–- CS443 js15.html 11.10.2011 -->
Object Example
<head>
<title>Dice page</title>
27
•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>
28
14
•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.
•Because we are using these tags inside of a JavaScript block, and they
are not JavaScript commands, we precede each of them with a
(JavaScript) comment marker, hence the two forward slashes before
each tag.
29
More to learn…
30
15
email: chungdt@soict.hust.edu.vn
Q&A
31
16