0% found this document useful (0 votes)
16 views

Javascript Mod3

Uploaded by

garyvee366
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Javascript Mod3

Uploaded by

garyvee366
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 199

JavaScript

Prof R Lokeshkumar
8/22/2024
Introduction
• JavaScript scripting language
• Enhances functionality and appearance
• Client-side scripting
• Makes pages more dynamic and interactive
• Web browser contains a JavaScript interpreter

• JavaScript is an Object Oriented Programming (OOP) language.


• Attributes (data) and behaviors (methods) are associated with the object.
JavaScript vs Java
• JavaScript is interpreted while Java is compiled
• But server-side JavaScript is compiled
• JavaScript is object-based while Java is object-oriented
• Object-based languages can utilize pre-defined objects, but you are limited in
terms of creating your own objects
• JavaScript has loose data typing, while Java has strong data typing
• Loose data typing means that a variable can hold any kind of data
• JavaScript has dynamic binding, while Java has static binding
• Names bound at runtime
• JavaScript can access browser objects and functionality, while Java cannot

3
What is JavaScript?
• Scripting language (object-oriented)
• Lightweight programming language developed by Netscape
• Interpreted, not compiled

• Designed to be embedded in browsers


• Ideal for adding interactivity to HTML pages
• Detect browser versions
• Work with info from user via HTML forms
• Create cookies
• Validate form data
• Read and write HTML elements

• Supported by all major browsers


What is JavaScript?
• Syntax is similar to Java, but it’s not Java form.
• Usually JavaScript code is embedded within HTML
code using the <script> tag:
• Can have more than one pair of script tags in a page
Client-Side JavaScript
• Detect whether the browser supports a certain plug-in
• Control a plug-in
• Validate user form input
• Prompt a user for confirmation
• Perform post-processing of information retrieved from
server-side JavaScript scripts

JavaScript 6
Client-Side JavaScript
• It was designed to provide a quicker and simpler language for
enhancing web pages and servers.
• Allows client browser to generate HTML on the fly.
• Java script provides increased functionality to the web browsers
• Provides a fairly complete set of Built in functions and commands to
perform Mathematical ,string functions & etc..
<noscript> tag
• Html uses this <noscript> tag to display an alternative
text if the browser does not support scripting
languages.
Programming Notes
• Javascript can be located in the head, body or external file

• Head section
• Ensures script is loaded before trigger event

• Body section
• Script executes when body loads

• External
• Allows scripts to run on several pages
JavaScript Program : Syntax
• Inline scripting
• Written in the <body> or <head> of a document
• <script> tag
• JavaScript Single-line comment symbol: //
• Example:
<script type= “text/javascript”>
<! - -
script code here
- - >
</script>
Programming with JavaScript (1)
• document object: the HTML document the browser is currently
displaying
• A statement should end with a semicolon (;)
• JavaScript is case sensitive.
• writeln method writes a line in the document
document.writeln(“<h1>Welcome</h1>”);
JavaScript - Variables

Variables in JavaScript are defined by using the var operator (short for variable),
followed by the variable name, such as:
var test = "hi";
In this example, the variable test is declared and given an initialization value of "hi"
(a string)
You can also define two or more variables using the same var statement:
var test = "hi", test2 = "hola";
Variables using the same var statement don't have to be of the same type:
var test = "hi", age = 25;
variables in JavaScript do not require initialization:
var test;
Javascript : Naming Variables

• The first character of the name must be a letter or an underscore (_).


• All characters following the first character can be letters, underscore, or digits.
• Letters can be either upper or lowercase.
• JavaScript does distinguish between the two cases.
• All the following variable names are legal:
var test;
var $test;
var $1;
var _$te$t2;
Javascript Variables : More
➢ Variables can hold different types of values at different times
➢ Variables don't have to be declared before being used
➢ Define variable and assign value
➢ Reassigning value to Variables
➢ Working With JavaScript Variables
➢ Declare two variables in the same line
➢ Reference a variable without declaration
➢ Assign one variable to another variable
➢ Do simple calculation
➢ Braces indicate code blocks Refer demo
Javascript :Variable Scope
• A variable can be either global or local in JavaScript.
• All variables are global unless they are declared in a function.
• Variables declared in a function is local to that function.
• It is possible for two variables with the same name to exist if one is global
and the other is local.
• When accessing the variable within the function, you are accessing the
local variable.
• If the variable is accessed outside the function, the global variable is used.
• Always use the var keyword to declare local variables in functions.
Refer Demo
JavaScript Output

• JavaScript Display Possibilities


• JavaScript can "display" data in different ways:

➢ HTML element, using innerHTML


➢ HTML output using document.write()
➢ Alert box, using window.alert()
➢ Browser console, using console.log()
Define message in one block and output it in another
<html>
<head>
<title>Define message in one block and output it in another</title>
<script language="javascript" type="text/javascript">
<!--
var msg = "Message in javascript";
//-->
</script>
</head>
<body>
<h1>Define message in one block and output it in another</h1>
<script language="javascript" type="text/javascript">
<!--
document.write("<P>" + msg + "</p>");
//-->
</script>
</body>
</html>
Reference javascript source file stored outside

<script src="path-to-file/fileName.js"></script>

JavaScript Can Change HTML Content

document.getElementById("demo").innerHTML

The Document method getElementById() returns an The Element property innerHTML gets or sets
Element object representing the element whose id the HTML or XML markup contained within the
property matches the specified string. Since element IDs element.
are required to be unique if specified, they're a useful way
to get access to a specific element quickly. Where ids are unique to the element, means it
can be used only to that particular tag and no
Refer Demo other tag should have same id
Javascript - innerHTML
• The innerHTML property can be used to write the dynamic html on the
html document.

• It is used mostly in the web pages to generate the dynamic html such as
registration form, comment form, links etc.

Syntax
const content = element.innerHTML;

element.innerHTML = htmlString;
Javascript - outerHTML
• The outerHTML attribute of the Element DOM interface gets the serialized
HTML fragment describing the element including its descendants.
• It can also be set to replace the element with nodes parsed from the given
string.
Syntax
var content = element.outerHTML;
element.outerHTML = htmlString;

Example
var d = document.getElementById("d");
console.writeline(d.outerHTML);

To only obtain the HTML representation of the contents of an element, or to replace the contents of an
element, use the innerHTML property instead
Number() Object
• Every number in JavaScript is treated as a floating-point number.
• JavaScript does support integers, octal, hexadecimal, and so on.
• At the lowest level, JavaScript sees numbers as floating-point numbers.

Syntax
var variable = new Number(value)

• The Number object represents numeric value types.


• You can create a Number object by specifying a value in the parameter for the
number constructor.
• Comparison of Number objects using == operator compares Number objects and
not the values.
Properties and Methods of the Number Object

MAX_VALUE Specifies the largest value a number can have.


MIN_VALUE Specifies the smallest value a number can have without being equal to 0.
Stands for Not a Number. Represents a value that is not equal to any numeric
NaN
value.
NEGATIVE_INFINITY A special value that represents a negative infinity value.

POSITIVE_INFINITY A special value that represents a positive infinity value.


prototype Represents the prototype for the number class.
toSource() Returns a string representation of the number object.
toString() Returns a string representing the specified number object.

valueOf() Returns the primitive value of a number object as a number data type.
Number Methods
Method Description
toExponential(fractionDigits) Returns exponential value as a string.

Example:
var num = 100; Num.toExponential(2); // returns '1.00e+2'
toFixed(fractionDigits) Returns string of decimal value of a number based on specified fractionDigits.

Example:
var num = 100; Num.toFixed(2); // returns '100.00'
toLocaleString() Returns a number as a string value according to a browser's locale settings.

Example:
var num = 100; Num.toLocaleString(); // returns '100'
toPrecision(precisionNumber) Returns number as a string with specified total digits.

Example:
var num = 100; Num.toPrecision(4); // returns '100.0'
toString() Returns the string representation of the number value.

Example:
var num = 100; Num.toString(); // returns '100'
valueOf() Returns the value of Number object.

Example: var num = new Number(100); Num.valueOf(); // returns '100'


DATE OBJECT
Date Object Properties

The JavaScript Date type stores dates as the number of milliseconds since
midnight on January 1, 1970 UTC (Universal Time Code).

Property Description
constructor Created the Date object
prototype Add properties and methods to an object

To create a date object:


//created object aDate is assigned the current date and time.
var aDate = new Date();
console.log(aDate)
Example 2
We can pass in a string value representing the date value.
The following date formats are supported:
var aDate = new Date(“Aug 25, 2020"); console.log(aDate);

Format Example
month/date/year 07/24/2012
month_name date, year January 31, 2021
day_of_week month_name date year hours:minutes:seconds Tue May 27 2012 12:34:56 GMT-0400
time_zone
ISO 8601 extended format YYYY-MM-DDTHH:mm:ss.sssZ 2012-0525T00:00:00
Example 3

We can pass in numbers to Date class constructors.


•the year,
•the zero-based month (January is 0, February is 1, and so on)
•the day of the month (1 through 31),
•the hours (0 through 23),
•minutes,
•seconds,
•Milliseconds

The year and month are required.


var aDate = new Date(2022, 4, 5, 17, 55, 55); console.log(aDate);
Example 4

If the day of the month isn't supplied, it's assumed to be 1 all


other omitted arguments are assumed to be 0.
var aDate = new Date(2021, 0); console.log(aDate);
//Sun Jan 01 2021 00:00:00 GMT-0800 (Pacific Standard Time)
Date Object Methods
Method Description
getDate() Returns the day of the month in int type from 1-31
getDay() Returns the day of the week from 0-6
getFullYear() Returns the year in four digits
getHours() Returns the hour and the value is from 0-23
getMilliseconds() Returns the milliseconds and the value is from 0-999
getMinutes() Returns the minutes and the value is from 0-59
getMonth() Returns the month whose value is from 0-11
getSeconds() Returns the seconds whose value is from 0-59
getTime() Returns the number of milliseconds since midnight Jan 1, 1970
getTimezoneOffset() Returns the time difference between UTC time and local time in
minutes
Date Object Methods(1)

getUTCDate() Returns the day of the month, according to universal time, value from 1-31

getUTCDay() Returns the day of the week, according to universal time, value from 0-6

getUTCFullYear() Returns the year, according to universal time in four digits


getUTCHours() Returns the hour, according to universal time, value from 0-23
getUTCMilliseconds() Returns the milliseconds, according to universal time, value from 0-999

getUTCMinutes() Returns the minutes, according to universal time, value from 0-59
getUTCMonth() Returns the month, according to universal time, value from 0-11
getUTCSeconds() Returns the seconds, according to universal time, value from 0-59
getYear() Deprecated. Use the getFullYear() method instead

parse() Parses a date string and returns the number of milliseconds since January 1, 1970

setDate() Sets the day of the month for a date object

setFullYear() Sets the year in four digits for a date object


setHours() Sets the hour of a date object
setMilliseconds() Sets the milliseconds of a date object

setMinutes() Set the minutes for a date object


setMonth() Sets the month for a date object
setSeconds() Sets the seconds for a date object
setTime() Sets a date to a number of milliseconds after/before January 1, 1970

setUTCDate() Sets the day of the month, according to universal time

setUTCFullYear() Sets the year in four digits, according to universal time (four digits)

setUTCHours() Sets the hour, according to universal time

setUTCMilliseconds() Sets the milliseconds, according to universal time

setUTCMinutes() Set the minutes, according to universal time


setUTCMonth() Sets the month, according to universal time
toDateString() Converts the date into a readable string for date part
toISOString() Convert the date to a string using the ISO standard format
toJSON() Convert the date to a string in a JSON date format
toLocaleDateString() Convert the date portion of a Date object to a string using current locale
toLocaleTimeString() Convert the time portion of a Date object to a string using locale conventions
toLocaleString() Convert a Date object to a string using locale conventions
toString() Convert a Date object to a string
toTimeString() Convert the time part of a Date object to a string
toUTCString() Convert a Date object to a string according to universal time
UTC() Create date from the number of milliseconds since midnight of January 1, 1970,
according to UTC time
valueOf() Convert date to its primitive value
setDate() Sets the day of the month for a date object
setFullYear() Sets the year in four digits for a date object
setHours() Sets the hour of a date object
setMilliseconds() Sets the milliseconds of a date object
setMinutes() Set the minutes for a date object
setMonth() Sets the month for a date object
setSeconds() Sets the seconds for a date object
setTime() Sets a date to a number of milliseconds after/before January 1, 1970

setUTCDate() Sets the day of the month, according to universal time


setUTCFullYear() Sets the year in four digits, according to universal time (four digits)

setUTCHours() Sets the hour, according to universal time


setUTCMilliseconds() Sets the milliseconds, according to universal time
setUTCMinutes() Set the minutes, according to universal time
setUTCMonth() Sets the month, according to universal time
setUTCSeconds() Set the seconds, according to universal time
JavaScript Objects – String,
Math

Prof R Lokeshkumar
8/22/2024
JavaScript: Objects

Introduction - Objects
Math Object
String Object
Fundamentals of Characters and Strings
Methods of the String Object
Character-Processing Methods
Searching Methods
Splitting Strings and Obtaining Substrings
HTML Markup Methods
Date Object
Boolean and Number Objects

2
Introduction
• Use JavaScript to manipulate every element of HTML document from
a script
• Reference for several of JavaScript’s built-in objects

3
Thinking About Objects
• Objects
• Attributes
• Behaviors
• Encapsulate date and methods
• Property of information hiding
• Details hidden within the objects themselves

4
Key Objects in JavaScript

• Key objects
➢ String
➢ Date
➢ Math
➢ Number and Boolean

5
String Object

• JavaScript’s string and character-processing capabilities


• Appropriate for processing names, addresses, credit card
information, etc.

Fundamentals of Characters and Strings


• Characters
• Fundamental building blocks of JavaScript programs
• String
• Series of characters treated as a single unit

6
Methods of the String Object
Method Description
charAt( index ) Returns a string containing the character at the specified index. If there is no
character at the index, charAt returns an empty string. The first character is
located at index 0.
charCodeAt( index ) Returns the Unicode value of the character at the specified index. If there is
no character at the index, charCodeAt returns NaN (Not a Number).
concat( string ) Concatenates its argument to the end of the string that invokes the method.
The string invoking this method is not modified; instead a new String is
returned. This method is the same as adding two strings with the string
concatenation operator + (e.g., s1.concat( s2 ) is the same as s1 +
s2).
fromCharCode( Converts a list of Unicode values into a string containing the corresponding
value1, value2, ) characters.
indexOf( Searches for the first occurrence of substring starting from position index in
substring, index ) the string that invokes the method. The method returns the starting index of
substring in the source string or –1 if substring is not found. If the index
argument is not provided, the method begins searching from index 0 in the
source string.
lastIndexOf( Searches for the last occurrence of substring starting from position index and
substring, index ) searching toward the beginning of the string that invokes the method. The
method returns the starting index of substring in the source string or –1 if
substring is not found. If the index argument is not provided, the method
begins searching from the end of the source string.

7
Methods of the String Object
slice( start, end ) Returns a string containing the portion of the string from index start
through index end. If the end index is not specified, the method returns a
string from the start index to the end of the source string. A negative end
index specifies an offset from the end of the string starting from a
position one past the end of the last character (so –1 indicates the last
character position in the string).
split( string ) Splits the source string into an array of strings (tokens) where its string
argument specifies the delimiter (i.e., the characters that indicate the end
of each token in the source string).
substr( Returns a string containing length characters starting from index start in
start, length ) the source string. If length is not specified, a string containing characters
from start to the end of the source string is returned.
substring( Returns a string containing the characters from index start up to but not
start, end ) including index end in the source string.
toLowerCase() Returns a string in which all uppercase letters are converted to lowercase
letters. Non-letter characters are not changed.
toUpperCase() Returns a string in which all lowercase letters are converted to uppercase
letters. Non-letter characters are not changed.
toString() Returns the same string as the source string.
valueOf() Returns the same string as the source string.

8
Methods of the String Object
Methods that generate
XHTML tags
anchor( name ) Wraps the source string in an anchor element
(<a></a>) with name as the anchor name.
blink() Wraps the source string in a <blink></blink>
element.
fixed() Wraps the source string in a <tt></tt>
element.
link( url ) Wraps the source string in an anchor element
(<a></a>) with url as the hyperlink location.
strike() Wraps the source string in a
<strike></strike> element.
sub() Wraps the source string in a <sub></sub>
element.
sup() Wraps the source string in a <sup></sup>
element.
Fig. 12.3 String object methods.

9
Character Processing Methods
• charAt
• Returns the character at specific position
• charCodeAt
• Returns Unicode value of the character at specific position
• fromCharCode
• Returns string created from series of Unicode values
• toLowerCase
• Returns lowercase version of string
• toUpperCase
• Returns uppercase version of string

10
Searching Methods
• indexOf and lastIndexOf
• Search for a specified substring in a string

11
Splitting Strings and Obtaining Substrings

• Tokenization
• The process of breaking a string into tokens
• Tokens
• Individual words
• Separated by delimiters
• String.split()
• String.substr(start[, length]) and String.substring(indexA, indexB)

12
HTML Markup Methods

• Anchor
• <a name = “top”> Anchor </a>
• Blink
• <blink> blinking text </blink>
• Fixed
• <tt> monospaced text </tt>
• Strike
• <strike> strike out text </strike>
• Subscript
• <sub> subscript </sub>
• Superscript
• <sup> superscript </sup>

13
Math Object
• Allow the programmer to perform many common mathematical
calculations

14
Math Object
Method Description Example
abs( x ) absolute value of x abs( 7.2 ) is 7.2
abs( 0.0 ) is 0.0
abs( -5.6 ) is 5.6
ceil( x ) rounds x to the smallest ceil( 9.2 ) is 10.0
integer not less than x ceil( -9.8 ) is -9.0
cos( x ) trigonometric cosine of x cos( 0.0 ) is 1.0
(x in radians)
exp( x ) exponential method ex exp( 1.0 ) is 2.71828
exp( 2.0 ) is 7.38906
floor( x ) rounds x to the largest floor( 9.2 ) is 9.0
integer not greater than x floor( -9.8 ) is -10.0
log( x ) natural logarithm of x log( 2.718282 ) is 1.0
(base e) log( 7.389056 ) is 2.0
max( x, y ) larger value of x and y max( 2.3, 12.7 ) is 12.7
max( -2.3, -12.7 ) is -2.3
15
Math Object
min( x, y ) smaller value of x min( 2.3, 12.7 ) is 2.3
and y min( -2.3, -12.7 ) is -12.7
pow( x, y ) x raised to power y pow( 2.0, 7.0 ) is 128.0
(xy) pow( 9.0, .5 ) is 3.0
round( x ) rounds x to the round( 9.75 ) is 10
closest integer round( 9.25 ) is 9
sin( x ) trigonometric sine of sin( 0.0 ) is 0.0
x (x in radians)
sqrt( x ) square root of x sqrt( 900.0 ) is 30.0
sqrt( 9.0 ) is 3.0
tan( x ) trigonometric tangent tan( 0.0 ) is 0.0
of x
(x in radians)
Fig. 12.1 Math object methods.

16
Math Object
Constant Description Value
Math.E Base of a natural Approximately 2.718.
logarithm (e).
Math.LN2 Natural logarithm of 2. Approximately 0.693.
Math.LN10 Natural logarithm of 10. Approximately 2.302.
Math.LOG2E Base 2 logarithm of e. Approximately 1.442.
Math.LOG10E Base 10 logarithm of e. Approximately 0.434.
Math.PI —the ratio of a circle’s Approximately
circumference to its 3.141592653589793.
diameter.
Math.SQRT1_2 Square root of 0.5. Approximately 0.707.
Math.SQRT2 Square root of 2.0. Approximately 1.414.
Fig. 12.2 Properties of the Math object.
17
Boolean and Number Objects

• Object wrappers for boolean true/false values and numbers

18
Boolean and Number Objects

Method Description
toString() Returns the string “true” if the value of the Boolean object is
true; otherwise, returns the string “false.”
valueOf() Returns the value true if the Boolean object is true; otherwise,
returns false.
Fig. 12.10 Boolean object methods.

19
Boolean and Number Objects
Method Description
toString() Returns the string “true” if the value of the Boolean object is
true; otherwise, returns the string “false.”
valueOf() Returns the value true if the Boolean object is true; otherwise,
returns false.
Fig. 12.10 Boolean object methods.

Method or Property Description


toString( radix ) Returns the string representation of the number. The optional radix
argument (a number from 2 to 36) specifies the number’s base.
valueOf() Returns the numeric value.
Number.MAX_VALUE This property represents the largest value that can be stored in a
JavaScript program—approximately 1.79E+308
Number.MIN_VALUE This property represents the smallest value that can be stored in a
JavaScript program—approximately
2.22E–308
Number.NaN This property represents not a number—a value returned from an
arithmetic expression that does not result in a number (e.g., the
expression parseInt( "hello" ) cannot convert the string
"hello" into a number, so parseInt would return
Number.NaN. To determine whether a value is NaN, test the
result with function isNaN, which returns true if the value is
NaN; otherwise, it returns false.
Number.NEGATIVE_INFINITY This property represents a value less than
-Number.MAX_VALUE.
Number.POSITIVE_INFINITY This property represents a value greater than
Number.MAX_VALUE.
Fig. 12.11 Number object methods and properties.
20
Module : 3
JavaScript Control Structures - I/O Statements -
Operators

Prof R Lokeshkumar
8/22/2024
JavaScript: Control
Structures
Introduction
• JavaScript scripting language
• Enhances functionality and appearance
• Client-side scripting
• Makes pages more dynamic and interactive
• Foundation for complex server-side scripting
• Program development
• Program control
What can JavaScript programs do?

• Giving the user more control over the browser


• Detecting the user's browser, OS, screen size, etc.
• Performing simple computations on the client side
• Validating the user's input
• Handling dates and time
• Generating HTML pages on-the-fly without accessing
the Web server.
What can’t JavaScript programs do?

• Use printers or other devices on the user's system or


the client-side LAN
• Directly access files on the user's system or the client-
side LAN ; the only exception is the access to the
browser's cookie files.
• Directly access files on the Web server.
• Implement multiprocessing or multithreading.
Programming context
• Interpreted language
• Web browser as the interpreter
• Client-side only
• Compatibility depends on browser version
• But virtually every browser supports JavaScript
• Follow ECMAScript standard!
• Security issues
• You cannot access the client’s system beyond their web browser
• Thus, no file access or direct printing
Object orientation in JavaScript
• JavaScript is an object-oriented programming language
• Based on objects with properties and methods
• JavaScript uses prototyping to replicate behaviour, rather than
classification (classes)
• There are two types of variables:
• Simple variables (also called “primitives”)
• Objects
Objects in JavaScript
• An object is a complex type of variable that contains its own variables
(properties), and has its own functions (methods)
• Properties
• The variables of an object
• Can also be other objects
• Methods
• The functions that belong to an object
• e.g. document.bgColor, window.location
• JavaScript has a rich set of built-in objects
• You can also define your own objects
How to specify JavaScript code
• Inline Code
• Add dynamic functionality to an individual element
• <img onMouseOver=“doThisFunction(this)”>
• Write JavaScript code directly in appropriate event attributes
• Embedded scripts
• Embed JavaScript code in an XHTML document—either in the head or in the body
• <script type=“text/javascript”> x=3; y=9; document.writeln( x + y );
</script>
• Inserting external scripts
• Insert a file with “.js” extension that contains JavaScript code
• <script type=“text/javascript” src=“external.js” />
• JavaScript libraries can be shared by multiple XHTML documents
• A note on CDATA
• <![CDATA[
]]>
• Necessary for legal XML to ignore & and < symbols (which are common in scripts)
• However, most browsers work fine without them
• http://www.w3schools.com/xml/xml_cdata.asp
• The textbook says to use <!-- comments to hide your code -->
• But CDATA is proper XML syntax
• Comments should validate, but not guaranteed
First scripts
Simple Program: Printing a Line of Text in a Web Page

• Inline scripting
• Written in the <body> of a document
• <script> tag
• Indicate that the text is part of a script
• type attribute
• Specifies the type of file and the scripting language use
• writeln method
• Write a line in the document
• Escape character ( \ )
• Indicates “special” character is used in the string
• alert method
• Dialog box
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 7.1: welcome.html -->
6 <!-- Displaying a line of text -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9
10
11
12
<head>

welcome.html
<title>A First Program in JavaScript</title>

<script type = "text/javascript">


13
14
15
<!--
document.writeln( (1 of 1)
"<h1>Welcome to JavaScript Programming!</h1>" );
16 // -->
17 </script>
18
19 </head><body></body>
20 </html>
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 7.2: welcome2.html -->
6 <!-- Printing a Line with Multiple Statements -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">

welcome2.html
9 <head>
10 <title>Printing a Line with Multiple Statements</title>
11
12 <script type = "text/javascript">
13
14
15
<!--
(1 of 1)
document.write( "<h1 style = \"color: magenta\">" );
document.write( "Welcome to JavaScript " +
16 "Programming!</h1>" );
17 // -->
18 </script>
19
20 </head><body></body>
21 </html>
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 7.3: welcome3.html -->
6 <!-- Printing Multiple Lines -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">

welcome3.html
9 <head><title>Printing Multiple Lines</title>
10
11 <script type = "text/javascript">
12 <!--
13
14
15
1 of 1
document.writeln( "<h1>Welcome to<br />JavaScript" +
"<br />Programming!</h1>" );
// -->
16 </script>
17
18 </head><body></body>
19 </html>
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 7.4: welcome4.html -->
6 <!-- Printing multiple lines in a dialog box -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">

welcome4.html
9 <head><title>Printing Multiple Lines in a Dialog Box</title>
10
11 <script type = "text/javascript">
12 <!--
13
14
15
// -->
</script>
1 of 1
window.alert( "Welcome to\nJavaScript\nProgramming!" );

16
17 </head>
18
19 <body>
20 <p>Click Refresh (or Reload) to run this script again.</p>
21 </body>
22 </html>
Illegal characters in
HTML vs. JavaScript
• HTML
• HTML entities
• &amp; &lt; &gt;
• JavaScript
• Escape sequences
• \’ \” \n \t \\
• To convert between the two,
use an HTML → JavaScript converter
• Google “HTML JavaScript converter”
Common escape sequences
Escape sequence Description
\n Newline. Position the screen cursor at the beginning of the next line.
\t Horizontal tab. Move the screen cursor to the next tab stop.
\r Carriage return. Position the screen cursor to the beginning of the
current line; do not advance to the next line. Any characters output
after the carriage return overwrite the characters previously output on
that line.
\\ Backslash. Used to represent a backslash character in a string.
\" Double quote. Used to represent a double quote character in a string
contained in double quotes. For example,
window.alert( "\"in quotes\"" );
displays "in quotes" in an alert dialog.

\' Single quote. Used to represent a single quote character in a string. For
example,
window.alert( '\'in quotes\'' );
displays 'in quotes' in an alert dialog.

Fig. 7.5 Some common escape sequences.


Dynamic Welcome Page
• A script can adapt the content based on input from the user or other
variables
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- Fig. 7.6: welcome5.html -->
6 <!-- Using Prompt Boxes -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">

welcome5.html
9 <head>
10 <title>Using Prompt and Alert Boxes</title>
11
12 <script type = "text/javascript">
13
14
15
<!--
(1 of 2)
var name; // string entered by the user

16 // read the name from the prompt box as a string


17 name = window.prompt( "Please enter your name", "GalAnt" );
18
19 document.writeln( "<h1>Hello, " + name +
20 ", welcome to JavaScript programming!</h1>" );
21 // -->
22 </script>
23
24 </head>
25
26 <body>
27 <p>Click Refresh (or Reload) to run this script again.</p>
28 </body>
29 </html>
Dynamic Welcome Page When the user clicks OK, the value
typed by the user is returned to the
program as a string.
This is the prompt
to the user.

This is the text field in which


This is the default value that the user types the value.
appears when the dialog
opens.
JavaScript data types
• In JavaScript, you can use the var statement to create a variable, but
it is not required
• You do not declare any data type (loosely typed)
• For scripting languages, data types are automatically determined
• Automatically converts between values of different types
• JavaScript data types
• Numbers
• Numbers are numbers, whether integer or floating point
• Boolean values
• true or false
• Strings
• “Anything within quotes”
• ‘Anything within quotes’
• Null
• "special key word denoting a null value"
• Means “no value”
Adding Integers
• Prompt user for two integers and calculate the sum (Fig. 7.8)
• NaN (not a number)
• parseInt
• Converts its string argument to an integer
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>An Addition Program</title>
11
12 <script type = "text/javascript">
13 <!--
14 var firstNumber, // first string entered by user
15 secondNumber, // second string entered by user
16 number1, // first number to add
17 number2, // second number to add
18 sum; // sum of number1 and number2
19
20
21
22
firstNumber =
Addition.html
// read in first number from user as a string

window.prompt( "Enter first integer", "0" );


23
24
25
26
secondNumber = (1 of 2)
// read in second number from user as a string

window.prompt( "Enter second integer", "0" );


27
28 // convert numbers from strings to integers
29 number1 = parseInt( firstNumber );
30 number2 = parseInt( secondNumber );
31
32 // add the numbers
33 sum = number1 + number2;
34
35 // display the results
36 document.writeln( "<h1>The sum is " + sum + "</h1>" );
37 // -->
38 </script>
39
40 </head>
41 <body>
42 <p>Click Refresh (or Reload) to run the script again</p>
43 </body>
44 </html>
JavaScript native functions

• parseInt()
• Converts a string into an integer, if possible
• parseFloat ()
• Converts a string into a floating-point number, if possible
• string ()
• Converts any object into a string
• number ()
• Converts any object into a number, if possible
• isNAN ()
• true if the object is Not A Number
• escape() and unescape()
• Converts and deconverts strings to “safe” characters
Operators in
JavaScript
Arithmetic operators
JavaScript Arithmetic Algebraic JavaScript
operation operator expression expression
Addition + f+7 f + 7

Subtraction - p–c x p - c
--
* y b * m
Multiplication bm
Division / x / y or or xy x / y

Remainder % r mod s r % s
Fig. 7.12 Arithmetic operators.

Operator(s) Operation(s) Order of evaluation (precedence)


*, / or % Multiplication Evaluated second. If there are several such
Division operations, they are evaluated from left to right.
Modulus
+ or - Addition Evaluated last. If there are several such operations,
Subtraction they are evaluated from left to right.
Fig. 7.13 Precedence of arithmetic operators.
Decision Making: Equality and Relational Operators
Standard algebraic JavaScript equality Sample Meaning of
equality operator or or relational JavaScript JavaScript
relational operator operator condition condition
Equality operators
= == x == y x is equal to y
? != x != y x is not equal to y
Relational operators
> > x > y x is greater than y
< < x < y x is less than y
>= x >= y x is greater than or
 equal to y
 <= x <= y x is less than or
equal to y
Fig. 7.15 Equality and relational operators.

Operators Associativity Type


* / % left to right multiplicative
+ - left to right additive
< <= > >= left to right relational
== != left to right equality
= right to left assignment
Fig. 7.17 Precedence and associativity of the
operators discussed so far.
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
3 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
4
5 <!-- Fig. 7.16: welcome6.html -->
6 <!-- Using Relational Operators -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">

welcome6.html
9 <head>
10 <title>Using Relational Operators</title>
11
12 <script type = "text/javascript">
13
14
15
<!--
(1 of 3)
var name, // string entered by the user
now = new Date(), // current date and time
16 hour = now.getHours(); // current hour (0-23)
17
18 // read the name from the prompt box as a string
19 name = window.prompt( "Please enter your name", "GalAnt" );
20
21 // determine whether it is morning
22 if ( hour < 12 )
23 document.write( "<h1>Good Morning, " );
24
25 // determine whether the time is PM
26 if ( hour >= 12 )
27 {
28 // convert to a 12 hour clock
29 hour = hour - 12;
30
31 // determine whether it is before 6 PM
32 if ( hour < 6 )

welcome6.html
33 document.write( "<h1>Good Afternoon, " );
34
35 // determine whether it is after 6 PM
36 if ( hour >= 6 )
37
38
39
} (2 of 3)
document.write( "<h1>Good Evening, " );

40 document.writeln( name +
41 ", welcome to JavaScript programming!</h1>" );
42 // -->
43 </script>
44
45 </head>
46
47 <body>
48 <p>Click Refresh (or Reload) to run this script again.</p>
49 </body>
50 </html>
Decision Making: Equality and Relational Operators

Operators Associativity Type


* / % left to right multiplicative
+ - left to right additive
< <= > >= left to right relational
== != left to right equality
= right to left assignment
Fig. 7.17 Precedence and associativity of the
operators discussed so far.
JavaScript: Control Statements I
Control Structures
• Sequential execution
• Statements execute in the order they are written
• Transfer of control
• Next statement to execute may not be the next one in sequence
• Three control structures
• Sequence structure
• Selection structure
• if
• if…else
• switch
• Repetition structure
• while
• do…while
• for
• for…in
JavaScript keywords
JavaScript
Keywords
break case catch continue default
delete do else finally for
function if in instanceof new
return switch this throw try
typeof var void while with
Keywords that
are reserved but
not currently
used by
JavaScript
abstract boolean byte char class
const debugger double enum export
extends final float goto implements
import int interface long native
package private protected public short
static super synchronized throws transient
volatile
Fig. 8.2 JavaScript keywords.
if Selection Statement
• Single-entry/single-exit structure
• Indicate action only when the condition evaluates to true
• Indicate different actions to be perform when condition is true or
false
• Conditional operator (?:)
• JavaScript’s only ternary operator
• Three operands
• Forms a conditional expression
while Repetition Statement
• Repetition structure (loop)
• Repeat action while some condition remains true
Formulating Algorithms with Top-Down, Stepwise Refinement:

• Consider problem
• Make observations
• Top-down, stepwise refinement
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 8.11: analysis.html -->
6 <!-- Analyzing Exam Results -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head> 25 if ( result == "1" )

10
11
12 <script type = "text/javascript">
analysis.html
<title>Analysis of Examination Results</title> 26
27
28
29
passes = passes + 1;
else
failures = failures + 1;

13
14
15
16
<!--

var passes = 0,
failures = 0,
(1 of 2)
// initializing variables in declarations
// number of passes
// number of failures
30
31
32
33
}
student = student + 1;

// termination phase
17 student = 1, // student counter 34 document.writeln( "<h1>Examination Results</h1>" );
18 result; // one exam result 35 document.writeln(

19 36 "Passed: " + passes + "<br />Failed: " + failures );


37
20 // process 10 students; counter-controlled loop
38 if ( passes > 8 )
21 while ( student <= 10 ) {
39 document.writeln( "<br />Raise Tuition" );
22 result = window.prompt(
40 // -->
23 "Enter result (1=pass,2=fail)", "0" );
41 </script>
24 42
43 </head>
44 <body>
45 <p>Click Refresh (or Reload) to run the script again</p>
46 </body>
47 </html>
More on JavaScript operators
Compound Assignment Operators
Assignment Initial Sample Explanation Assigns
operator value of expression
variable
+= c = 3 c += 7 c = c + 10 to c
7
-= d = 5 d -= 4 d = d - 1 to d
4
*= e = 4 e *= 5 e = e * 20 to e
5
/= f = 6 f /= 3 f = f / 2 to f
3
%= g = 12 g %= 9 g = g % 3 to g
9
Fig. 8.12 Arithmetic assignment operators.
Increment and Decrement Operators
• Preincrement or predecrement operator
• Increment of decrement operator placed before a variable
• Postincrement or postdecrement operator
• Increment of decrement operator placed after a variable
Increment and Decrement Operators
Operator Called Sample Explanation
expression
++ preincrement ++a Increment a by 1, then use the
new value of a in the
expression in which a resides.
++ postincrement a++ Use the current value of a in
the expression in which a
resides, then increment a by 1.
-- predecrement --b Decrement b by 1, then use the
new value of b in the
expression in which b resides.
-- postdecrement b-- Use the current value of b in
the expression in which b
resides, then decrement b by 1.
Fig. 8.13 increment and decrement operators.
5 <!-- Fig. 8.14: increment.html -->
6 <!-- Preincrementing and Postincrementing -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Preincrementing and Postincrementing</title>
11
12 <script type = "text/javascript">

increment.html
13 <!--
14 var c;
15
16 c = 5;
17
18
19
(1 of 2)
document.writeln( "<h3>Postincrementing</h3>" );
document.writeln( c );
// print 5 then increment
// print 5

20 document.writeln( "<br />" + c++ );


21 document.writeln( "<br />" + c ); // print 6
22
23 c = 5;
24 document.writeln( "<h3>Preincrementing</h3>" );
25 document.writeln( c ); // print 5
26 // increment then print 6
27 document.writeln( "<br />" + ++c );
28 document.writeln( "<br />" + c ); // print 6
29 // -->
30 </script>
31
32 </head><body></body>
33 </html>
Increment and Decrement Operators
Operator Associativity Type
++ -- right to left unary
* / % left to right multiplicative
+ - left to right additive
< <= > >= left to right relational
== != left to right equality
?: right to left conditional
= += -= *= /= %= right to left assignment
Fig. 8.15 Precedence and associativity of the operators
discussed so far.
JavaScript: Control Statements II
Essentials of Counter-Controlled Repetition
• Counter-controlled repetition
• Name of a control
• Initial value
• Increment or decrement
• Final value
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 9.1: WhileCounter.html -->
6 <!-- Counter-Controlled Repetition -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">

WhileCounter.html
9 <head>
10 <title>Counter-Controlled Repetition</title>
11
12 <script type = "text/javascript">
13
14
15
<!--
(1 of 2)
var counter = 1; // initialization

16 while ( counter <= 7 ) { // repetition condition


17 document.writeln( "<p style = \"font-size: " +
18 counter + "ex\">XHTML font size " + counter +
19 "ex</p>" );
20 ++counter; // increment
21 }
22 // -->
23 </script>
24
25 </head><body></body>
26 </html>
for Repetition Statement
• for repetition statement
• Handles all the details of counter-controlled repetition
• for structure header
• The first line
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 9.2: ForCounter.html -->
6 <!-- Counter-Controlled Repetition with for statement -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">

ForCounter.html
9 <head>
10 <title>Counter-Controlled Repetition</title>
11
12 <script type = "text/javascript">
13
14
15
<!--

(1 of 1)
// Initialization, repetition condition and
// incrementing are all included in the for
16 // statement header.
17 for ( var counter = 1; counter <= 7; ++counter )
18 document.writeln( "<p style = \"font-size: " +
19 counter + "ex\">XHTML font size " + counter +
20 "ex</p>" );
21 // -->
22 </script>
23
24 </head><body></body>
25 </html>
for Repetition Statement
forkeyword Control variable name Final value of control variable
for which the condition is true

for ( var counter = 1; counter <= 7; ++counter )

Initial value of control variable Increment of control variable


Loop-continuation condition
Examples Using the for Statement

• Summation with for


• Compound interest calculation with for loop
• Math object
• Method pow
• Method round
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 9.5: Sum.html -->
6 <!-- Using the for repetition statement -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">

Sum.html
9 <head>
10 <title>Sum the Even Integers from 2 to 100</title>
11
12 <script type = "text/javascript">
13
14
15
<!--
var sum = 0; (1 of 1)
16 for ( var number = 2; number <= 100; number += 2 )
17 sum += number;
18
19 document.writeln( "The sum of the even integers " +
20 "from 2 to 100 is " + sum );
21 // -->
22 </script>
23
24 </head><body></body>
25 </html>
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Calculating Compound Interest</title>
11
12 <script type = "text/javascript">
13 <!--
14 var amount, principal = 1000.0, rate = .05;
15
16 document.writeln(
17
18
19
20
document.writeln(
Interest.html
"<table border = \"1\" width = \"100%\">" );

"<caption>Calculating Compound Interest</caption>" );


document.writeln(
21
22
23
24
document.writeln(
(1 of 2)
"<thead><tr><th align = \"left\">Year</th>" );

"<th align = \"left\">Amount on deposit</th>" );


document.writeln( "</tr></thead>" );
25
26 for ( var year = 1; year <= 10; ++year ) {
27 amount = principal * Math.pow( 1.0 + rate, year );
28 document.writeln( "<tbody><tr><td>" + year +
29 "</td><td>" + Math.round( amount * 100 ) / 100 +
30 "</td></tr>" );
31 }
32
33 document.writeln( "</tbody></table>" );
34 // -->
35 </script>
36
37 </head><body></body>
38 </html>
switch Multiple-Selection Statement
• Controlling expression
• Case labels
• Default case
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 9.7: SwitchTest.html -->
6 <!-- Using the switch statement -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">

SwitchTest.html
9 <head>
10 <title>Switching between XHTML List Formats</title>
11
12 <script type = "text/javascript">
13
14
15
<!--
var choice,
startTag,
(1 of 3)
// user’s choice
// starting list item tag
16 endTag, // ending list item tag
17 validInput = true, // indicates if input is valid
18 listType; // list type as a string
19
20 choice = window.prompt( "Select a list style:\n" +
21 "1 (bullet), 2 (numbered), 3 (lettered)", "1" );
22
23 switch ( choice ) {
24 case "1":
25 startTag = "<ul>";
26 endTag = "</ul>";
27 listType = "<h1>Bullet List</h1>";
28 break;
29 case "2":
30 startTag = "<ol>";
31 endTag = "</ol>";
32 listType = "<h1>Ordered List: Numbered</h1>";
33 break;
34
35
36
37
case "3":

SwitchTest.html
startTag = "<ol type = \"A\">";
endTag = "</ol>";
listType = "<h1>Ordered List: Lettered</h1>";

(2 of 3)
38 break;
39 default:
40 validInput = false;
41 }
42
43 if ( validInput == true ) {
44 document.writeln( listType + startTag );
45
46 for ( var i = 1; i <= 3; ++i )
47 document.writeln( "<li>List item " + i + "</li>" );
48
49 document.writeln( endTag );
50 }
51 else
52 document.writeln( "Invalid choice: " + choice );
53 // -->
54 </script>
55
56 </head>
57 <body>
58 <p>Click Refresh (or Reload) to run the script again</p>
59 </body>
do…while Repetition Statement
• Similar to the while statement
• Tests the loop continuation condition after the loop body executes
• Loop body always executes at least once
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 9.9: DoWhileTest.html -->
6 <!-- Using the do...while statement -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Using the do...while Repetition Statement</title>
11
12 <script type = "text/javascript">
13 <!--
14 var counter = 1;
15
16 do {
17 document.writeln( "<h" + counter + ">This is " +
18 "an h" + counter + " level head" + "</h" +
19 counter + ">" );
20
21 ++counter;
22 } while ( counter <= 6 );
23 // -->
24 </script>
25
26 </head><body></body>
27 </html>
break and continue Statements
• break
• Immediate exit from the structure
• Used to escape early from a loop
• Skip the remainder of a switch statement
• continue
• Skips the remaining statements in the body of the structure
• Proceeds with the next iteration of the loop
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 9.11: BreakTest.html -->
6 <!-- Using the break statement -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">

BreakTest.html
9 <head>
10 <title>
11 Using the break Statement in a for Structure
12 </title>
13
14
15 <!--
(1 of 2)
<script type = "text/javascript">

16 for ( var count = 1; count <= 10; ++count ) {


17 if ( count == 5 )
18 break; // break loop only if count == 5
19
20 document.writeln( "Count is: " + count + "<br />" );
21 }
22
23 document.writeln(
24 "Broke out of loop at count = " + count );
25 // -->
26 </script>
27
28 </head><body></body>
29 </html>
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 9.12: ContinueTest.html -->
6 <!-- Using the break statement -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">

ContinueTest.html
9 <head>
10 <title>
11 Using the continue Statement in a for Structure
12 </title>
13
14
15 <!--
(1 of 2)
<script type = "text/javascript">

16 for ( var count = 1; count <= 10; ++count ) {


17 if ( count == 5 )
18 continue; // skip remaining code in loop
19 // only if count == 5
20
21 document.writeln( "Count is: " + count + "<br />" );
22 }
23
24 document.writeln( "Used continue to skip printing 5" );
25 // -->
26 </script>
27
28 </head><body></body>
29 </html>
Labeled break and continue Statements

• Labeled break statement


• Break out of a nested set of structures
• Immediate exit from that structure and enclosing repetition structures
• Execution resumes with first statement after enclosing labeled statement
• Labeled continue statement
• Skips the remaining statements in structure’s body and enclosing repetition structures
• Proceeds with next iteration of enclosing labeled repetition structure
• Loop-continuation test evaluates immediately after the continue statement executes
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Using the break Statement with a Label</title>
11
12 <script type = "text/javascript">
13 <!--
14 stop: { // labeled block
15 for ( var row = 1; row <= 10; ++row ) {
16 for ( var column = 1; column <= 5 ; ++column ) {
17
18 if ( row == 5 )
19 break stop; // jump to end of stop block
20
21 document.write( "* " );
22 }
23
24 document.writeln( "<br />" );
25 }
26
27 // the following line is skipped
28 document.writeln( "This line should not print" );
29 }
30
31 document.writeln( "End of script" );
32 // -->
33 </script>
34
35 </head><body></body>
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 9.14: ContinueLabelTest.html -->
6 <!-- Using the continue statement -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10
11
12
ContinueLabelTest.html
<title>Using the continue Statement with a Label</title>

<script type = "text/javascript">


13
14
15
<!--
nextRow: (1 of 2)
// target label of continue statement
for ( var row = 1; row <= 5; ++row ) {
16 document.writeln( "<br />" );
17
18 for ( var column = 1; column <= 10; ++column ) {
19
20 if ( column > row )
21 continue nextRow; // next iteration of
22 // labeled loop
23
24 document.write( "* " );
25 }
26 }
27 // -->
28 </script>
29
Logical operators
Logical Operators
• More logical operators
• Logical AND ( && )
• Logical OR ( || )
• Logical NOT ( ! )
Logical Operators
expression1 expression2 expression1 &&
expression2
false false false
false true false
true false false
true true true
Fig. 9.15 Truth table for the && (logical AND)
operator.
Logical Operators
expression1 expression2 expression1 ||
expression2
false false false
false true true
true false true
true true true
Fig. 9.16 Truth table for the || (logical OR) operator.

expression !expression
false true
true false
Fig. 9.17 Truth table for operator ! (logical negation).
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
5 <!-- Fig. 9.18: LogicalOperators.html -->
6 <!-- Demonstrating Logical Operators -->
7
8 <html xmlns = "http://www.w3.org/1999/xhtml">
9 <head>
10 <title>Demonstrating the Logical Operators</title>
11
12 <script type = "text/javascript">
13 <!--
14 document.writeln(
15 "<table border = \"1\" width = \"100%\">" );
16 26 "<br />true && true: " + ( true && true ) +
17 document.writeln( 27 "</td>" );
18 "<caption>Demonstrating Logical " + 28
19 "Operators</caption" ); 29 document.writeln(
20 30 "<tr><td width = \"25%\">Logical OR (||)</td>" +
21 document.writeln( 31 "<td>false || false: " + ( false || false ) +
22 "<tr><td width = \"25%\">Logical AND (&&)</td>" + 32 "<br />false || true: " + ( false || true ) +
23 "<td>false && false: " + ( false && false ) + 33 "<br />true || false: " + ( true || false ) +
24 "<br />false && true: " + ( false && true ) + 34 "<br />true || true: " + ( true || true ) +
25 "<br />true && false: " + ( true && false ) +
35 "</td>" );
36
37 document.writeln(
38 "<tr><td width = \"25%\">Logical NOT (!)</td>" +
39 "<td>!false: " + ( !false ) +
40 "<br />!true: " + ( !true ) + "</td>" );
41
42 document.writeln( "</table>" );
43 // -->
44 </script>
45
46 </head><body></body>
47 </html>
Logical Operators
Operator Associativity Type
++ -- ! right to left unary
* / % left to right multiplicative
+ - left to right additive
< <= > >= left to right relational
== != left to right equality
&& left to right logical AND
|| left to right logical OR
?: right to left conditional
= += -= *= /= %= right to left assignment
Fig. 9.19 Precedence and associativity of the operators discussed
so far.
Module : 3
Java Script - Functions

Prof R Lokeshkumar
2

JavaScript Functions

Outline
Introduction
Program Modules in JavaScript
Programmer-Defined Functions
Function Definitions
Random Number Generation
Duration of Identifiers
Scope Rules
JavaScript Global Functions
3
Introduction

• Programs that solve real-world programs


– More complex than programs from previous chapters

• Best way to develop & maintain large program:


– Construct from small, simple pieces called modules
– Technique called divide and conquer
4
Program Modules in JavaScript

• functions – JavaScript modules


• JavaScript programs written by combining
– Functions programmer writes
– “prepackaged” functions and objects in JavaScript
• These functions often called methods
• Implies function belongs to particular object
• JavaScript provides several rich objects for performing
– Common mathematical operations
– String manipulation
– Date and time manipulation
– Manipulations of arrays
5
Program Modules in JavaScript

• Programmer-defined functions
– Written by programmer to define specific tasks
– Statements defining functions written once
– Statements are hidden from other functions
• Function is invoked by a function call
– Specifies function name
– Provides information (or arguments) function needs for
execution
• Function call syntax:
functionName( argument );
6
Programmer-Defined Functions

• Functions allow program modularization


• Variables declared in function are local variables
– Only known inside function in which defined
• Most functions have list of parameters
– Means for communicating info between functions &
function calls
– Local variables
– When function called, arguments assigned to parameters in
function definition
7
Programmer-Defined Functions

• Motives for modularizing a program with functions


1. Makes program development more manageable
2. Allows software reusability
• Programs can be created from standard functions instead of being
built from customized code
Example: parseInt(), parseFloat
• Functions should be limited to performing a single, well-defined
task
3. Avoid repeating code in program
• Do not re-invent the wheel
• Save time
8
Programmer-Defined Functions

• Naming functions
– Choose concise names which describe what function does
– If not possible to describe briefly, your function is too
complex
9
Function Definitions

• Function-definition format
function function-name ( parameter-list )
{
Declarations and Statements
}
– Function name - any valid identifier
– Parameter list - comma-separated list containing names of
parameters received by the function when it is called
– If function does not receive values, parameter-list is left
empty
10
Function Definitions

• Function body or block:


– declarations and statements within braces
• Control
– Returned to the point at which function was called
– If function does not return a result
1. When right-brace is reached return statement is executed
– If function returns a result
3. When return expression; is executed
• Returns value of expressions to caller
1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
2 <HTML>
3 <!-- Fig. 16.2: SquareInt.html -->
4 1.1 Output HTML
5 <HEAD>
6 <TITLE>A Programmer-Defined square Function</TITLE>
7
2.1 Open for control
8 <SCRIPT LANGUAGE = "JavaScript">
structure
9 document.writeln(
10 "<H1>Square the numbers from 1 to 10</H1>" ); 2.2 Call square user-
11 defined function
12 // square the numbers from 1 to 10
13 for ( var x = 1; x <= 10; ++x )
3.1 Define square function
14 document.writeln( "The square of " + x + " is " +
15 square( x ) + "<BR>" );
16 3.2 Return result
17 // The following square function's body is executed only
18 // when the function is explicitly called.
19
20 // square function definition
21 function square( y )
22 {
23 return y * y;
24 }
25 </SCRIPT>
26
27 </HEAD><BODY></BODY>
28 </HTML>
12

Script Output
13
Function Definitions

• Method Math.max( y, z )
– Returns larger of the two values inputted
• When writing a function, do not
– Forget to return a value if function is supposed to return a
value
– Forget to surround the function body with braces
– Pass an argument to function that is not compatible with
expected data type
1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
2 <HTML>
3 <!-- Fig. 16.3: maximum.html -->
4
1.1 Define variables and
5 <HEAD>
prompt user for values
6 <TITLE>Finding the Maximum of Three Values</TITLE>
7
8 <SCRIPT LANGUAGE = "JavaScript"> 1.2 Convert strings to
9 var input1 = window.prompt( "Enter first number", "0" ); integers
10 var input2 = window.prompt( "Enter second number", "0" );
11 var input3 = window.prompt( "Enter third number", "0" );
2.1 Execute user-defined
12
function maxValue
13 var value1 = parseFloat( input1 );
14 var value2 = parseFloat( input2 );
15 var value3 = parseFloat( input3 ); 3.1 Print results
16
17 var maxValue = maximum( value1, value2, value3 );
4.1 Define function
18
maxValue
19 document.writeln( "First number: " + value1 +
20 "<BR>Second number: " + value2 +
21 "<BR>Third number: " + value3 +
22 "<BR>Maximum is: " + maxValue );
23
24 // maximum method definition (called from line 17)
25 function maximum( x, y, z )
26 {
27 return Math.max( x, Math.max( y, z ) );
28 }
29 </SCRIPT>
30
31 </HEAD>
32 <BODY>
33 <P>Click Refresh (or Reload) to run the script again</P>
34 </BODY>
35 </HTML>

User Input
16
Script Output
17

Random Number Generation

• Commonly used in simulations and gaming


• Method Math.random
– Returns floating-point value between 0 and 1, inclusive
– Every value in the range has an equal chance (or
probability) of being chosen each time random called

• Math.floor( argument );
– Rounds down the argument to the next integer
18
Random Number Generation

• Format for range of consecutive integers:


– For a value in a specific range of consecutive integers, use
following format:

Math.floor( a + Math.random() * b );
– a is the shifting value
• Equal to the first number in the desired range
– b is the scaling factor
• Equal to the width of the desired range
– Also possible to choose from sets of values other than
ranges of consecutive integers
1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
2 <HTML>
3 <!-- Fig. 16.4: RandomInt.java -->
4
1.1 Initialize variable
5 <HEAD>
6 <TITLE>Shifted and Scaled Random Integers</TITLE>
7 2.1 Initialize HTML TABLE
8 <SCRIPT LANGUAGE = "JavaScript">
9 var value;
3.1 Start for structure
10
11 document.writeln( "<H1>Random Numbers</H1>" +
12 "<TABLE BORDER = '1' WIDTH = '50%'><TR>" ); 3.2 Set value to random
13 value
14 for ( var i = 1; i <= 20; i++ ) {
15 value = Math.floor( 1 + Math.random() * 6 );
3.2.1 Call Math.random
16 document.writeln( "<TD>" + value + "</TD>" );
17
18 if ( i % 5 == 0 && i != 20 ) 3.2.2 Set desired range for
19 document.writeln( "</TR><TR>" ); random number
20 } generation
21
22 document.writeln( "</TR></TABLE>" );
3.3.3 Call Math.floor
23 </SCRIPT>
24
25 </HEAD> 4.1 Print results
26 <BODY>
27 <P>Click Refresh (or Reload) to run the script again</P>
28 </BODY>
29 </HTML>
20
Script Outputs
21
Duration of Identifiers

• Each identifier has duration and scope


– Duration (or lifetime) is the period during which identifier
exists in memory.
• Some identifiers exist briefly
• Some identifiers are repeatedly created and destroyed
• Some identifiers exist for entire execution of the program
• Identifiers which represent local variables in a function
have automatic duration
– Automatically created when program control enters function
– Exist while function is active
– Automatically destroyed when function is exited
– Referred to as local variables
22
Duration of Identifiers

• JavaScript also has identifiers of static duration


– Typically defined in <HEAD> section of HTML document
– Exist from point at which declared until browsing session
over
– Even though they exist after <HEAD> section terminates,
cannot necessarily be used throughout the script
– Referred to as global variables or script-level variables
23
Scope Rules
• Scope of identifier is portion of program in which
identifier can be referenced
– Local variable declared in a function can be used only in that
function
• Identifiers declared inside a function have function (or
local) scope
– Begins with opening brace ({) of function
– Ends with closing brace(}) of function
– Function parameters also have local scope
– If local variable has same name as global variable, global
variable “hidden” from body of function
1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
2 <HTML>
3 <!-- Fig. 16.7: scoping.html -->
4
1.1 Initialize variable
5 <HEAD>
6 <TITLE>A Scoping Example</TITLE>
7 2.1 Define start()
8 <SCRIPT LANGUAGE = "JavaScript"> function
9 var x = 1; // global variable
10
2.2 State start function
11 function start()
actions
12 {
13 var x = 5; // variable local to function start
14 2.3 Call user defined
15 document.writeln( "local x in start is " + x ); functions
16
17 functionA(); // functionA has local x
2.4 Print results
18 functionB(); // functionB uses global variable x
19 functionA(); // functionA reinitializes local x
20 functionB(); // global variable x retains its value 3.1 Define function
21 functionA()
22 document.writeln(
23 "<P>local x in start is " + x + "</P>" );
24 }
25
26 function functionA()
27 {
28 var x = 25; // initialized each time functionA is called
29
30 document.writeln( "<P>local x in functionA is " + x +

31 " after entering functionA" );

32 ++x;
3.2 Demonstrate function
33 document.writeln( "<BR>local x in functionA is " + x + scope
34 " before exiting functionA</P>" );
4.1 Define functionB()
35 }

36
4.2 Demonstrate global
37 function functionB() scope
38 {

39 document.writeln( "<P>global variable x is " + x +

40 " on entering functionB" );

41 x *= 10;

42 document.writeln( "<BR>global variable x is " + x +

43 " on exiting functionB</P>" );

44 }

45 </SCRIPT>

46

47 </HEAD>

48 <BODY ONLOAD = "start()"></BODY>

49 </HTML>
26

Script Output:
27

JavaScript Global Functions

• Global functions are part of JavaScript’s Global


object
– Contains all global variables in the script
– Some programmers refer to these functions as methods
• Global functions and user-defined functions part of Global object
• You do not need to use the Global object directly
– JavaScript does this for you
28
JavaScript Global Functions
Glob a l func tion Desc rip tion
escape This function takes a string argument and returns a string in which all
spaces, punctuation, accent characters and any other character that is
not in the ASCII character set (see Appendix C, “ASCII Character
Set”) are encoded in a hexadecimal format (see the “Number Systems”
document on the CD that accompanies this book) that can be
represented on all platforms.
eval This function takes a string argument representing JavaScript code to
execute. The JavaScript interpreter evaluates the code and executes it
when the eval function is called. This function allows JavaScript
code to be stored as strings and executed dynamically.
isFinite This function takes a numeric argument and returns true if the value
of the argument is not NaN, Number.POSITIVE_INFINITY or
Number.NEGATIVE_INFINITY; otherwise the function returns
false.
isNaN This function takes a numeric argument and returns true if the value
of the argument is not a number; otherwise the function returns
false. The function is commonly used with the return value of
parseInt or parseFloat to determine whether the result is a
proper numeric value.
29
JavaScript Global Functions
Continued from previous slide
Glob a l func tion Desc rip tion
parseFloat This function takes a string argument and attempts to convert the
beginning of the string into a floating-point value. If the conversion is
not successful, the function returns NaN; otherwise, it returns the
converted value (e.g., parseFloat( "abc123.45" ) returns NaN
and parseFloat( "123.45abc" ) returns the value 123.45.
parseInt This function takes a string argument and attempts to convert the
beginning of the string into an integer value. If the conversion is not
successful, the function returns NaN; otherwise, it returns the converted
value (e.g., parseInt( "abc123" ) returns NaN and parseInt(
"123abc" ) returns the integer value 123. This function takes an
optional second argument from 2 to 36 specifying the radix (or base) of
the number. Base 2 indicates that the first argument string is in binary
format, 8 indicates that the first argument string is in octal format and
16 indicates that the first argument string is in hexadecimal format. See
see the “Number Systems” document on the CD that accompanies this
book for more information on binary, octal and hexadecimal numbers.
unescape This function takes a string as its argument and returns a string in
which all characters that we previously encoded with escape are
decoded.
Form controls - Regular Expression –
Event Handling

Prof R Lokeshkumar
Form Validation
◼ Before an HTML form is submitted, JavaScript can be
used to provide client-side data validation
◼ This is more user-friendly for the user than server-
side validation because it does not require a server
round trip before giving feedback
◼ If the form is not valid, the form is not submitted until
the errors are fixed
Client-Side Validation
HTTP Request

HTTP Response

Web Browser Application Database


Web Server
Server Server

JavaScript Application
Validation Validation

◼ JavaScript data validation happens before form is


submitted
◼ Server-side application validation happens after the
form is submitted to the application server
Client-Side Validation
◼ If creating a Web form, make sure the data submitted
is valid and in the correct format
◼ Client-side validation gives the user faster feedback
◼ If possible, allow for server-side validation if the
JavaScript is turned off
What to Validate on a Form?
◼ Form data that typically are checked by a
JavaScript could be:
◼ were required fields left empty?

◼ was a valid e-mail address entered?

◼ was a valid date entered?

◼ was text entered in a numeric field?

◼ were numbers entered in an text field?

◼ did the number entered have a correct range?


onchange Validation
◼ To force the browser to check each field
immediately, we add an onchange event to each
of the <input> tags in the form
◼ For example: if we wanted to check if the value of
a certain text field had a valid e-mail address we
would add this:
<input type="text" name="EMail" size="20"
onchange="emailvalidation(this);" >
<form> onsubmit Event
◼ Your form must have a Submit button the user clicks
when completing the form
◼ An onsubmit event will be raised and you should
put this code in the <form> tag
◼ Call your event handler to go through and test each
form field as needed
◼ If the event handler returns false, the form
submission will be cancelled, if true the form will
submit and the form action will be executed
<form action="Process.php” onsubmit="return validate(this);” >
onsubmit Event Handler
◼ Pass the form object as the this parameter
◼ onsubmit=“return validate(this);”
◼ This function should create variables for each field
that needs validation
◼ Set a inputvalid = true to begin with
◼ Use a series of if statements to perform each
validation test, if test fails set inputvalid =false and
set error message and/or alert message
◼ Finally, return inputvalid from the event handler
function validate(form) {
// Set each of needed form variables
General
var input valid=true; Event Handler
var message=“Please fix the following errors \n”;
Structure
if (!testFunction(text)) {
// something is wrong
// message =+ “new error \n”;
// validinput= false;
}
if (!testFunction2(text)) {
// something else is wrong
// message =+ “new error \n”;
// validinput= false;
}
// do each validation test
if(!validinput) {
alert (message);
}
return validinput;
}
Testing for Required Entry
◼ Checking a textbox field could be done with a
simple test for text.length == 0
◼ Checking a select field to see if an option has
been selected use selectedIndex>0
◼ Place instruction text as the first <option>
◼ Checking a checkbox checked==true
◼ Checking a radiobutton need to loop through
array and test each checked==true
◼ May want to always set a default radio button as
selected=“selected”
Regular Expressions
◼ You can use a symbol representation of a string value
called a regular expression to test your input text
◼ There are many regular expressions available for
common tests
◼ U.S. Phone: /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/
◼ Email: /^[0-9a-zA-Z]+@[0-9a-zA-Z]+[\.]{1}
[0-9a-zA-Z]+[\.]?[0-9a-zA-Z]+$/
Regular Expression Syntax

var pattern = new RegExp (pattern, attributes);


or
var pattern = /pattern/attributes;

• Pattern − A string that specifies the pattern of the regular


expression or another regular expression.
• Attributes − An optional string containing any of the "g", "i",
and "m" attributes that specify
• g-global
• i- case-insensitive
• m- multiline matches
• caret (^) - indicate the beginning of the string
• dollar sign ($) - used to mark the end
Examples
• JavaScript // Matches "Isn't JavaScript great?“
• ^JavaScript // Matches "JavaScript rules!", // not "What is
JavaScript?"
• JavaScript$ // Matches "I love JavaScript", // not
"JavaScript is great!"
• ^JavaScript$ // Matches "JavaScript", and nothing else
JavaScript Regular Expressions

A regular expression is a particular representation


of a set of strings
◼ Ex: JavaScript regular expression representing

the set of syntactically-valid US telephone area


codes (three-digit numbers):

⚫ \d represents the set {“0”, “1”, …, “9”}


⚫ Concatenated regular expressions represent the
“concatenation” (Cartesian product) of their sets
Using match() method to validate regular expression for
phone number (e.g. (123) 456-7890)

function checkPhoneNumber(phoneNo)
{
var phoneRE = /^\(\d\d\d\) \d\d\d”-”\d\d\d\d$/;
if (phoneNo.match(phoneRE))
{
return true;
}
else { alert( "The phone number entered is invalid!" );
return false;
}
}
Example Regular Expression
◼ Test to see if text is a number
◼ Returns true if number, false otherwise
◼ Does the text match the pattern?

// check if the text is a number


function IsNumber(fData)
{
var reg = /^[0-9]+[\.]?[0-9]+$/;
return reg.test(fData)
}
JAVASCRIPT EVENT HANDLING
l Basic Event Handling
There are quite a few different event-handler attributes that you can use in
l

the original event model.


They are :
l

• onblur
• onchange
• onclick
• onfocus
• onkeydown
• onkeypress
• onkeyup
• onload
• onmousedown
• onmousemove
• onmouseout
• onmouseover
• onmouseup
• onsubmit
• onunload
l Intrinsic Event Attributes
Event Intrinsic Event Attribute
Load onLoad (associated with windows, images)
Unload onUnload (associated only with windows)
Click onClick (associated with any elements)
MouseOver onMouseOver (associated with any elements)
MouseOut onMouseOut (associated with any elements)
Focus onFocus (associated with windows, frames, links, and form
elements)
Blur onBlur (associated with windows, frames, links, and form
elements)
Submit onSubmit (associated with forms)
Reset onReset (associated with forms)
Select onSelect (associated with text boxes, password, text areas)
Change onChange (associated with text boxes, text areas, password, file
uploads, select lists)
Event handler Applies to: Triggered when:
onAbort Image The loading of the image is cancelled.
onBlur Button, Checkbox, Password, The object in question loses focus (e.g. by
Radio, Reset, Select, Submit, clicking outside it or pressing the TAB key).
Text, TextArea, Window
onChange Select, Text, TextArea The data in the form element is changed by the
user.
onClick Button, Checkbox, Link, Radio, The object is clicked on.
Reset, Submit
onDblClick Document, Link The object is double-clicked on.
onError Image A JavaScript error occurs.
onFocus Button, Checkbox, Password, The object in question gains focus (e.g. by
Radio, Reset, Select, Submit, clicking on it or pressing the TAB key).
Text, TextArea
onKeyDown Image, Link, TextArea The user presses a key.
onKeyPress Image, Link, TextArea The user presses or holds down a key.
onKeyUp Image, Link, TextArea The user releases a key.
onLoad Image, Window The whole page has finished loading.
onMouseDown Button, Link The user presses a mouse button.
onMouseMove None The user moves the mouse.
onMouseOut Image, Link The user moves the mouse away from the object.

onMouseOver Image, Link The user moves the mouse over the object.
onMouseUp Button, Link The user releases a mouse button.
onMove Window The user moves the browser window or frame.

onReset Form The user clicks the form's Reset button.


onResize Window The user resizes the browser window or frame.
l Event – onload
<html>
<head>
<script language= "JavaScript" type="text/javascript">
function mymessage()
{
alert("This message was triggered from the onload event");
}
</script>
</head>
<body onload="mymessage()">
</body>
</html>
l Event – onunload

<html>
<head>
<script type="text/javascript">
function mymessage()
{
alert("This message was triggered from the onunload event");
}
</script>
</head>
<body onunload="mymessage()">
<p>An alert box will display a message when you close this
document!</p>
</body>
</html>
l Event – onchange
<HTML>
<TITLE>Example of onChange Event Handler</TITLE>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function valid(){
var input=0;
input=document.myform.data.value;
alert("You have changed the value from 10 to " + input );
}
</SCRIPT>
</HEAD>
<BODY>
<H3>Example of onChange Event Handler</H3>
Try changing the value from 10 to something else:<br>
<form name="myform">
<input type="text" name="data" value="10" size=10 onChange= "valid( )">
</form>
</BODY>
</HTML>
l Event – onsubmit

<html>
<head>
<script type="text/javascript">
function confirmInput()
{
fname=document.forms[0].fname.value;
alert("Hello " + fname + "! You will now be redirected to some other
page");
}
</script>
</head>
<body>
<form onsubmit="confirmInput()" action="http://www.w3c.org">
Enter your name: <input id="fname" type="text" size="20">
<input type="submit">
</form>
</body>
</html>
l Event – onblur

<html>
<head>
<script type="text/javascript">
function message()
{
alert("This alert box was triggered by the onblur event handler");
}
</script>
</head>
<body>
<p>The onblur event occurs when an element loses focus. Try to click or
write in the input field below, then click elsewhere in the document so the
input field loses focus.</p>
<form>
Enter your name: <input type="text" onblur="message()" size="20">
</form>
</body>
</html>
l Event – onfocus

<html>
<head>
<script type="text/javascript">
function message()
{
alert("This alert box was triggered by the onfocus event handler");
}
</script>
</head>
<body>
<form>
Enter your name: <input type="text" onfocus="message()" size="20">
</form>
</body>
</html>
l Event – onmouseover & onmouseout sample

<html>
<body>

<h1 onmouseover="style.color='red'“ onmouseout=


"style.color='green'">
Mouse over this text</h1>

</body>
</html>
l Event – onclick

<html>
<head>
<script type="text/javascript">
function disp_func()
{
Alert(“This alert box was triggered by the onclick event handler”);
}
</script>
</head>
<body>
<input type=“button” value=click to display message” onclick= “disp_func();”
>
</body>
</html>
l Event – onmousemove

<html>
<head>
<script type="text/javascript">
var i=1;
function moveright()
{
document.getElementById('header').style.position="relative";
document.getElementById('header').style.left=i;
i++;
}
</script>
</head>
<body onmousemove="moveright()">
<h1 id="header">
Move the mouse over this page
</h1>
</body>
</html>
Errors

• Syntax Errors
• Syntax errors, also called parsing errors, occur at compile time in
traditional programming languages and at interpret time in
JavaScript.
• Runtime Errors
• Runtime errors, also called exceptions, occur during execution (after
compilation/interpretation).
• Logical Errors
• Logic errors can be the most difficult type of errors to track down.
These errors are not the result of a syntax or runtime error. Instead,
they occur when you make a mistake in the logic that drives your
script and you do not get the result you expected.
Form controls - Regular Expression –
Event Handling

Prof R Lokeshkumar
Error and Exception Handling in JavaScript
• Javascript makes no distinction between Error and Exception (Unlike Java)

• Handling Exceptions
• The onError event handler
• A method associated with the window object.
• It is called whenever an exception occurs
• The try … catch … finally block
• Similar to Java try … catch … finally block
• For handling exceptions in a code segment
• Use throw statement to throw an exception
• You can throw value of any type
• The Error object
• Default object for representing an exception
• Each Error object has a name and message properties
The onerror() Method

•The onerror event handler was the first


feature to facilitate error handling in
JavaScript.
•The onerror event handler provides three
pieces of information to identify the exact
nature of the error −
• Error message − The same message that the browser
would display for the given error
• URL − The file in which the error occurred
• Line number− The line number in the given URL that
caused the error
How to use “onError” event handler?
<html>
<head>
<title>onerror event handler example</title>
<script type="text/javascript">
function errorHandler(){
alert("Error Ourred!");
}
// JavaScript is casesensitive
// Don't write onerror!
window.onError = errorHandler;
</script>
</head>
<body>
<script type="text/javascript">
document.write("Hello there;
</script>
</body>
</html>
try … catch … finally
try {
// Contains normal codes that might throw an exception.

// If an exception is thrown, immediately go to


// catch block.

} catch ( errorVariable ) {
// Codes here get executed if an exception is thrown
// in the try block.

// The errorVariable is an Error object.

} finally {
// Executed after the catch or try block finish

// Codes in finally block are always executed


}
// One or both of catch and finally blocks must accompany the try
block.
try … catch … finally example
<script type="text/javascript">
try{
document.write("Try block begins<br>");
// create a syntax error
eval ("10 + * 5");

} 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>
JavaScript:
BOM and DOM

9/20/2024
revisit
Web Browsers and Objects

Object type:Window
Properties
Location: http://www.vit.ac.in

Object type:Document
Properties
URL: https://vit.ac.in/files/ebooks/Research-Promotion-Policy/index.html

9/20/2024
revisit
BOM: Browser Object Model
• BOM – collection of objects that the browser makes available
to us for use with JavaScript

window O bject

location Object history O bject document O bject


Object navigator O bject screen Object

DOM

… ……
Object
form O
form bject Object
link O
link bject Object
image O
image bject

9/20/2024
revisit
DOM: Document Object Model

Object type:Document
Properties
URL: https://vit.ac.in/files/ebooks/Research-Promotion-Policy/index.html

Event Happens when


Load page and content have finished loading
Click user clicks the mouse over the page
Keypress user presses down on a key

Method W hat it does


write() adds content to the document
getElementById() accesses an element of a given id attribute

9/20/2024
Using BOM Objects
(Some Properties)
Property Description
window.screenX X-coordinate of pointer, relative to top left corner
of screen (in pixels)
window.screenY Y-coordinate of pointer, relative to top left corner
of screen (in pixels)
window.location Current URL of window object
window.document Reference to document object
window.history Reference to history object for browser window
or tab, which contains details of the pages that
have been viewed in that window or tab
window.history.length Number of items in history object
window.screen Reference to screen object
window.screen.width Accesses width property of screen object
window.screen.height Accesses height property of screen object

9/20/2024
Using BOM Objects
(Some Methods)
Method Description
window.alert( ) Create modal dialog box with message (user must
click OK button to close it)
window.open(url) Open new browser window with the specified URL
window.print( ) Tell browser that user wants to print contents of
current page (act like user has clicked a print option)
window.history.back( ) Move backward through history
window.history.forward( ) Move forward through history
window.history.go(step) Move to specific page from session history (step
specifies the number of pages, forward or
backward)
history.pushState(state, Create a new entry (or add a URL) at the top of the
title, url) browser history
history.replaceState(state, Modify the current entry (current URL at the top) of
title, url) the browser history

9/20/2024
Using DOM Objects
• Not part of HTML

• Separate rules implemented by all major browser markers

• Two primary purposes:


• Making a model of the HTML page
• Specifies how browsers should create a model of an HTML page

• Accessing and changing the HTML page


• Specifies how JScan access and update the contents of a web page

9/20/2024
DOM: Four Types of Nodes
document Document node
Element node
<html>

<head> <body>

<meta> <title> <link> <a> <table>

http-equiv CBS3014 rel name top align center <tr>


content- (Programming stylesheet width 100%
type Language for href
Content Web styles/cs4640
text/html Applications) -style.css <td>
... ...

width 75% <font> <font>


align center

Text node Attribute node size +2 <strong> size +2 <strong>


color red

Syllabus — Fall 2024

9/20/2024
Using DOM Objects
(Some Properties and Methods)
Property Description
document.title Title of current document
document.lastModified Date on which document was last modified
document.URL String containing URL of current document
document.domain Domain of current document

Method Description
document.write( ) Write text to document
document.getElementById(id) Return element whose id attribute matches
the specified id
document.querySelectorAll(selector) Return list of elements that match the
specified CSS selector
document.createElement(element) Create new element
document.createTextNode(text) Create new text node

9/20/2024

You might also like