Javascript Mod3
Javascript Mod3
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
3
What is JavaScript?
• Scripting language (object-oriented)
• Lightweight programming language developed by Netscape
• Interpreted, not compiled
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
<script src="path-to-file/fileName.js"></script>
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)
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.
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
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
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
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
setUTCFullYear() Sets the year in four digits, according to universal time (four digits)
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
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
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.
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?
• 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>
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
• & < >
• 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.
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
• 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.
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
• 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(
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
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
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
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%\">" );
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">
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">
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
• 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
• 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
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
• Math.floor( argument );
– Rounds down the argument to the next integer
18
Random Number Generation
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
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 {
41 x *= 10;
44 }
45 </SCRIPT>
46
47 </HEAD>
49 </HTML>
26
Script Output:
27
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
JavaScript Application
Validation Validation
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?
• 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.
<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>
</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
} 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>
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
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
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
9/20/2024
DOM: Four Types of Nodes
document Document node
Element node
<html>
<head> <body>
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