Javascript in Unit2 Part1
Javascript in Unit2 Part1
The Basics
5
History
▪ JavaScript created by Netscape
▪ JScript created by Microsoft
▪ IE and Netscape renderings are slightly different
6
JavaScript / JScript
▪ Different brands or/and different versions of
browsers may support different implementation of
JavaScript.
▪ They are not fully compatible
8
Java vs. JavaScript
▪ Requires the JDK to create the ▪ Requires a text editor
applet ▪ Required a browser that can
▪ Requires a Java virtual interpret JavaScript code
machine to run the applet
▪ JavaScript can be placed
▪ Applet files are distinct from
the XHTML code within HTML and XHTML
▪ Source code is hidden from the ▪ Source code is made
user accessible to the user
▪ Programs must be saved as ▪ Programs cannot write content
separate files and compiled to the hard disk
before they can be run ▪ Programs run on the client side
▪ Programs run on the server
side
9
Other Client-side Languages
▪ Internet Explorer supports JScript.
▪ JScript is identical to JavaScript, but there are some
JavaScript commands not supported in JScript, and
vice versa.
▪ Other client-side programming languages are also
available to Web page designers, such as the
Internet Explorer scripting language, VBScript.
10
What can we do with JavaScript?
▪ To create interactive user interface in a web
page (e.g., menu, pop-up alert, windows, etc.)
13
Using the <script> Tag
14
A Simple Script
<html>
<head><title>First JavaScript Page</title></head>
<body>
<h1>First JavaScript Page</h1>
<script type="text/javascript">
document.write("<hr>");
document.write("Hello World Wide Web");
document.write("<hr>");
</script>
</body>
</html>
Embedding JavaScript
<html>
<head><title>First JavaScript Program</title></head>
<body>
<script type="text/javascript"
src="your_source_file.js"></script>
</body>
</html> Inside your_source_file.js
document.write("<hr>");
document.write("Hello World Wide Web");
document.write("<hr>");
document.write('This is my first →
JavaScript Page');
document.write('<h1>This is my first →
JavaScript Page</h1>');
26
User input/output
<SCRIPT TYPE="text/javascript">
var firstNumber, // first string entered by user
secondNumber, // second string entered by user
number1, // first number to add
number2, // second number to add
sum; // sum of number1 and number2
// read in first number from user as a string
firstNumber = window.prompt("Enter first integer", "0" );
// read in second number from user as a string
secondNumber = window.prompt( "Enter second integer", "0" );
// convert numbers from strings to integers
firstNumber = parseInt(firstNumber);
number2 = parseInt( secondNumber );
// add the numbers
sum = firstNumber + number2;
// display the results
document.writeln( "<H1>The sum is " + sum + "</H1>" );
</SCRIPT>
27
Creating JavaScript Functions
28
Creating JavaScript Functions
function function_name(parameters) {
JavaScript commands
}
29
Functions
<SCRIPT TYPE = "text/javascript">
var input1 = window.prompt( "Enter first number", "0" );
var input2 = window.prompt( "Enter second number", "0"
);
var input3 = window.prompt( "Enter third number", "0" );
var value1 = parseFloat( input1 );
var value2 = parseFloat( input2 );
var value3 = parseFloat( input3 );
var maxValue = maximum( value1, value2, value3 );
document.writeln( "First number: " + value1 +
"<BR>Second number: " + value2 +
"<BR>Third number: " + value3 +
"<BR>Maximum is: " + maxValue );
// maximum method definition (called from above)
function maximum( x, y, z ) {
return Math.max( x, Math.max( y, z ) );
}
</SCRIPT>
30
Random Numbers
<SCRIPT TYPE="text/javascript">
var value;
document.writeln( "<H1>Random Numbers</H1>" +
"<TABLE BORDER = '1' WIDTH = '50%'><TR>" );
for ( var i = 1; i <= 20; i++ ) {
value = Math.floor( 1 + Math.random() * 6 );
document.writeln( "<TD>" + value + "</TD>" );
if ( i % 5 == 0 && i != 20 )
document.writeln( "</TR><TR>" );
}
document.writeln( "</TR></TABLE>" );
</SCRIPT>
31
Identifier
▪ Same as Java/C++ except that it allows an
additional character – '$'.
▪ Contains only 'A' – 'Z', 'a' – 'z', '0' – '9', '_', '$'
▪ First character cannot be a digit
▪ Case-sensitive
▪ Cannot be reserved words or keywords
Variable and Variable Declaration
<head><script type="text/javascript">
// We are in the default scope – the "window" object.
x = 3; // same as "window.x = 3"
var y = 4; // same as "y = 4" or "window.y = 4"
</script></head>
42
Null & Undefined
▪ An undefined value is represented by the
keyword "undefined".
▪ It represents the value of an uninitialized variable
44
Operators
46
Operators
▪ The decrement operator reduces the value of a
variable by 1.
x = 100;
y = x--;
▪ The negation operator changes the sign of a
variable:
x = -100;
y = -x;
47
Assignment Operators
48
Assignment Operators
Comparison, Logical, and
Conditional Operators
50
An Example of
Boolean Expressions
▪ x < 100;
▪ if x is less than 100, this expression returns the value
true; however, if x is 100 or greater, the expression is
false
▪ y == 20;
▪ the y variable must have an exact value of 20 for the
expression to be true
▪ comparison operator uses a double equal sign (==)
51
Comparison Operators
52
A Logical Operator
▪ The logical operator && returns a value of true only if all
of the Boolean expressions are true.
53
A Conditional Operator
tests whether a specific condition is true and returns one
value if the condition is true and a different value if the
condition is false.
▪ Message = (mail == “Yes”) ? “You have mail”: “No
mail”;
▪ tests whether the mail variable is equal to the value
“Yes”
▪ if it is, the Message variable has the value “You have mail”;
▪ otherwise, the Message variable has the value “No mail”.
54
Working with Conditional Statements
if (condition) {
JavaScript Commands
}
▪ condition is an expression that is either true or false
▪ if the condition is true, the JavaScript Commands in
the command block are executed
▪ if the condition is not true, then no action is taken
55
Using an if...else Statement
if (condition) {
JavaScript Commands if true
} else
JavaScript Commands if false
}
▪ condition is an expression that is either true or false,
and one set of commands is run if the expression is
true, and another is run if the expression is false
56
if...else Conditional Statement
document.write("Today is " + ThisMonth +
"/“+ThisDay+"/"+ThisYear+"<br />");
if (DaysLeft > 0) {
document.write("Only "+DaysLeft+
" days until Christmas");
} else {
document.write("Happy Holidays from
Nroth Pole Novelties");
}
Using an if...else if Statement
if (condition) {
JavaScript Commands if true
} else if (cond)
JavaScript Commands if false
}
else
{}
▪ condition is an expression that is either true or false,
and one set of commands is run if the expression is
true, and another is run if the expression is false
58
Using switch Statement
switch (expr) {
case val:…
break;
default: stmts;
59
Working with Program Loops
60
The For Loop
61
The For Loop Continued
62
Specifying Counter Values in a For Loop
“for/in” statement
for (var variable in object) {
statements;
}
68
do{
Stmts;
}
while (condition)
69
Built-In Functions
▪ eval(expr)
▪ evaluates an expression or statement
▪ eval("3 + 4"); // Returns 7 (Number)
▪ eval("alert('Hello')"); // Calls the function alert('Hello')
▪ isFinite(x)
▪ Determines if a number is finite
▪ isNaN(x)
▪ Determines whether a value is “Not a Number”
Built-In Functions
▪ parseInt(s)
▪ parseInt(s, radix)
▪ Converts string literals to integers
▪ Parses up to any character that is not part of a valid integer
▪ parseInt("3 chances") // returns 3
▪ parseInt(" 5 alive") // returns 5
▪ parseInt("How are you") // returns NaN
▪ parseInt("17", 8) // returns 15
▪ parseFloat(s)
▪ Finds a floating-point value at the beginning of a string.
▪ parseFloat("3e-1 xyz") // returns 0.3
▪ parseFloat("13.5 abc") // returns 13.5
Creating Objects
▪ JavaScript is not an OOP language.
▪ "prototype" is the closest thing to "class" in
JavaScript.
alert(triangle.p1.y); // Show 3
Object Constructor and prototyping
function Person(fname, lname) {
// Define and initialize fields
this.firstName = fname;
this.lastName = lname;
// Define a method
this.sayHi = function() {
alert("Hi! " + this.firstName + " " +
this.lastName);
}
}
<html>
<head>
<title>onMouseOver / onMouseOut Event Handler Demo</title>
</head>
<body>
<a href="http://www.cuhk.edu.hk"
onMouseOver="window.status='CUHK Home'; return true;"
onMouseOut="status=''"
>CUHK</a>
</body>
</html>
• When the mouse cursor is over the link, the browser displays the text
"CUHK Home" instead of the URL.
• The "return true;" of onMouseOver forces browser not to display the URL.
• window.status and window.defaultStatus are disabled in Firefox.
onSubmit Event Handler Example
<html><head>
<title>onSubmit Event Handler Example</title>
<script type="text/javascript">
function validate() {
// If everything is ok, return true
// Otherwise return false
}
</script>
</head>
<body>
<form action="MessageBoard" method="POST"
onSubmit="return validate();"
>
…
</form></body></html>
} catch ( errorVariable ) {
// Codes here get executed if an exception is thrown
// in the try block.
} finally {
// Executed after the catch or try block finish
} catch( errVar ) {
document.write("Exception caught<br>");
// errVar is an Error object
// All Error objects have a name and message properties
document.write("Error name: " + errVar.name + "<br>");
document.write("Error message: " + errVar.message +
"<br>");
} finally {
document.write("Finally block reached!");
}
</script>
Throwing Exception
<script type="text/javascript">
try{
var num = prompt("Enter a number (1-2):", "1");
// You can throw exception of any type
if (num == "1")
throw "Some Error Message";
else
if (num == "2")
throw 123;
else
throw new Error ("Invalid input");
} catch( err ) {
alert(typeof(errMsg) + "\n" + err);
// instanceof operator checks if err is an Error object
if (err instanceof Error)
alert("Error Message: " + err.message);
}
</script>