0% found this document useful (0 votes)
3 views260 pages

Javascript

JavaScript is essential for web development, alongside HTML and CSS, as it enables dynamic behavior on web pages. It can manipulate HTML content, validate inputs, and interact with users through various methods. The document also covers JavaScript's structure, data types, functions, and control statements, providing examples for practical understanding.

Uploaded by

CR7 Ronaldo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views260 pages

Javascript

JavaScript is essential for web development, alongside HTML and CSS, as it enables dynamic behavior on web pages. It can manipulate HTML content, validate inputs, and interact with users through various methods. The document also covers JavaScript's structure, data types, functions, and control statements, providing examples for practical understanding.

Uploaded by

CR7 Ronaldo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 260

Web Technologies

JavaScript1

Mamatha

BMSCE, ISE 1
Why Study JavaScript?

JavaScript is one of the 3 languages all web developers must


learn.

1. HTML to define the content of web pages

2. CSS to specify the layout of web pages

3. JavaScript to program the behavior of web pages

BMSCE, ISE 2
What can JavaScript do ?

JavaScript can change HTML content


JavaScript can change CSS style properties
JavaScript can validate input
JavaScript can change HTML attributes
JavaScript can make interactions with users through form elements,
such as buttons and menus

BMSCE, ISE 3
Three parts of Javascript
• Core JavaScript
Includes operators, expressions, statements and
subprograms (heart of language)
• Client-side JavaScript
A collection of objects that support control of browser
and interactions with user. Eg: with javascript, an HTML
document can be made to respond to user inputs such
as mouse clicks and keyboard use.
• Server-side JavaScript
A collection of objects that make the language useful on
a web server. For eg: to support communication with a
DBMS, file operations and networking.

BMSCE, ISE 4
JavaScript Reserved words

Break Delete Function Return typeof

case Do If Switch Var

Catch Else In This Void

Continue Finally Instanceof Throw While

Default for new try with

BMSCE, ISE 5
First JavaScript Program
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
<!--
document.write("First JavaScript Program in
Web Technologies");
//-->
</script>
</body>
</html>

Sample I/O:

BMSCE, ISE 6
JavaScript: Where To Place?
Two different ways to embed JavaScript in an HTML Document:
1. Explicit Embedding
2. Implicit Embedding : External file

Explicit Embedding: JavaScript code physically resides in the


HTML document.
Inside <head> tag : Scripts that produce content only when
requested or that react to user interactions are placed in
the head of the document.
These scripts contain function definitions and code
associated with form elements such as buttons.

Inside <body> tag : Scripts that are to be interpreted just


once, when the interpreter finds them, are placed in the
body.
BMSCE, ISE 7
Example3.html

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript"> program1.js
document.write("JavaScript inside document.write
Head tag","<br />"); ("JavaScript inside
</script> </head> External file","<br />");
<body>
<script type="text/javascript">
document.write("JavaScript inside
Body tag","<br />");
</script>
<script src = program1.js"> Sample I/O:

</script>
</body>
</html>

BMSCE, ISE 8
JavaScript Data Types
JavaScript variables can hold many primitive data types:
Numbers,
Strings,
Boolean,
Undefined : If a variable is explicitly declared, but not assigned a
value, it has value undefined.

Null: A variable is null if it has not been explicitly declared or


assigned a value.

var num = 17; // Number

var lastName = “Rao"; // String


Boolean: T/F
Undefined: undefined var
Null: No value

BMSCE, ISE 9
JavaScript functions for string manipulation
1. length: a value which holds the number of characters
2. charAt(index): function returns the character which is at position
index in the string
3. concat(“string” [, “string” [, . . . “string”]]):
4. indexOf(“search” [,offset]): returns the position in string object of
the parameter
5. lastIndexOf(“search” [,offset]): searches backwards of indexOf
6. Split(separator [,limit]): function breaks the string apart whenever
it encounters the character passed in as the first parameter. Limit
is an integer value indicating how many of pieces are to be stored
in array
7. Substr(index [,length])
8. toLowerCase()
9. toUpperCase()
10. Substring(index [,index2]): similar to substr but not includes the
char at index2.
BMSCE, ISE 10
String Methods : Example
s[0] s[1] s[2] s[3] s[4] s[5] s[6] s[7] s[8] s[9]
b m s c o l l e g e

var s="bmscollege"; var str=“George”;

s.charAt(2) is ‘s’ str.indexOf(‘r’) is 3


s.indexOf('c') is 3 str.charAt(2) is ‘0’
s.substring(3,6) is col
s.substr(3,6) is coll str.substring(2,4) is ‘or’
str.toLowerCase() is ‘george’

BMSCE, ISE 11
Example to find length of string:
<!DOCTYPE html>
<html>
<head>
<title> Exercise to find length of string</title>
</head>
<body> Sample I/O:
<script type="text/javascript">
<!--
var str="Bangalore";
var len=str.length;
document.write("Length of string
\"Bangalore\" is :" ,len,"<br />");
//-->
</script>
</body></html>
BMSCE, ISE 12
Example for charAt() function:
<!DOCTYPE html> Sample I/O:
<html>
<head>
<title> Exercise for charAt function of
string</title>
</head>
<body>
<script type="text/javascript">
<!--
var you=prompt("Enter your name:", " ");
document.write("The character at position in your
name is :" , you.charAt(4));
//-->
</script>
BMSCE, ISE 13
</body></html>
Example for substr and substring functions:
<!DOCTYPE html>
<html>
<head>
<title> Exercise for substr and substring functions of string</title>
</head>
<body>
<script type="text/javascript">
<!--
var str="Bangalore";
document.write("substr function on string Bangalore (1,4) is: "+str.substr(1,4)+"<br />");
document.write("substring function on string Bangalore (1,4) is: "+str.substring(1,4));
//-->
</script>
</body></html>

Sample I/O:

BMSCE, ISE 14
Example for split function:
<!DOCTYPE html>
<html>
<head>
<title> Exercise for split function of string</title>
</head>
<body>
<script type="text/javascript">
<!--
var str="Bangalore one today";
document.write("split function on string Bangalore one today with Blank as separator is:
"+str.split(" ") +"<br />");
document.write("split function on string Bangalore one today is: "+str.split(""));
//--></script>
</body></html>

Sample I/O:

BMSCE, ISE 15
Screen Output and Keyboard Input:

Screen Output method1:alert() method

• The alert() method displays an alert box with a specified message and
an OK/Close button.
• An alert box is often used if you want to make sure information
comes through to the user.

BMSCE, ISE 16
Example Program : alert
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript">
alert("Welcome to BMSCE");
</script> Sample I/O:
</body>
</html>

BMSCE, ISE 17
Screen Output method2:confirm()
method

• The confirm() method displays a dialog box with a specified


message, along with an OK and a Cancel button.
• A confirm box is often used if you want the user to verify or
accept something.
• The confirm() method returns true if the user clicked "OK",
and false otherwise.

BMSCE, ISE 18
Example Program : confirm
<!DOCTYPE html>
<html>
<body>
<script>
var txt;
var r = confirm("Press a button!");
if (r == true) {
txt = "You pressed OK!";
alert(txt);
} else {
txt = "You pressed Cancel!";
alert(txt);
}
</script>
</body>
</html>

BMSCE, ISE 19
Example program output1

If you click on OK button, output is as shown below

BMSCE, ISE 20
Example program output2

If you click on Cancel button, output is as shown below

BMSCE, ISE 21
Screen Output method3:
prompt() method

• The prompt() method displays a dialog box that prompts the


visitor for input.
• A prompt box is often used if you want the user to input a
value before entering a page.
• The prompt() method returns the input value if the user
clicks "OK". If the user clicks "cancel" the method returns
null

BMSCE, ISE 22
Example program: Prompt
<!DOCTYPE html>
<html>
<body> Sample I/O:
<script>
var txt;
var r = prompt("Enter your name:");

if (r == true) {
txt = "You pressed OK!";
alert(txt);
} else {
txt = "You pressed Cancel!";
alert(txt);
}
</script>
</body>
</html>
BMSCE, ISE 23
Dialog Windows

Alert alert("Welcome to BMSCE


Window WebTechnologies course");

Confirm registration=confirm(
Window "Do You want to register for 8th
Sem ?");

Prompt name=prompt("Enter your


Window name:");

BMSCE, ISE 24
Keyboard Input

• Write some text directly to the HTML output:


Eg: document.write("Hello World!");

• Write some HTML elements directly to the HTML output:


Eg: document.write("<h2>Hello World!</h2><p>Have a nice
day!</p>");

BMSCE, ISE 25
<!DOCTYPE html>
<html>
<body>
<h1>The Document Object</h1>
<h2>The write() Method</h2>
<p>Write some text directly to the HTML
output:</p>
<script>
document.write("Hello World!");
</script>
<h2>The Lorem Ipsum Passage</h2>
<p>This is Lorem ipsum dolor sit amet,
consectetur adipiscing elit, sed do Sample I/O:
eiusmod tempor incididunt ut labore et
dolore magna aliqua.</p>
</body>
</html>

BMSCE, ISE 26
<!DOCTYPE html>
<html> <body>
<h1>The Document Object</h1>
<h2>The write() Method</h2>
<p>Write some HTML elements directly to
the HTML output:</p>
<script>
document.write("<h2>Hello
World!</h2><p>Have a nice day!</p>");
</script>
<h2>The Lorem Ipsum Passage</h2>
<p>
This is Lorem ipsum dolor sit amet,
consectetur adipiscing elit, sed do eiusmod Sample I/O:
tempor incididunt ut labore et dolore magna
aliqua.
</body>
</html>

BMSCE, ISE 27
Selection Statements:

JavaScript If...Else Statements


if (condition) {
block of code to be executed if the condition is true
} else {
block of code to be executed if the condition is false
}

if (condition1) {
block of code to be executed if condition1 is true
} else if (condition2) {
block of code to be executed if the condition1 is false and condition2 is
true
} else {
block of code to be executed if the condition1 is false and condition2 is
false
}

BMSCE, ISE 28
JavaScript script To find Largest of
three numbers
<!DOCTYPE html>
<html> <body>
<script type="text/javascript">
{
var n1=Number(prompt("Enter number 1: "));
var n2=Number(prompt("Enter number 2: "));
var n3=Number(prompt("Enter number 3: "));
if (n1>n2 && n1>n3)
alert(n1+" is largest");
else if(n2>n3)
alert(n2+" is largest");
else
alert(n3+" is largest");
}
</script>
</body></html>
BMSCE, ISE 29
Sample I/O:

BMSCE, ISE 30
Javascript Switch Statement
• Use the switch statement to select one of many blocks of code to be
executed.
• General Syntax:
switch(expression) {
case n1:
code block
break;
case n2:
code block
break;
default:
default code block
}
This is how it works:
• The switch expression is evaluated once.
• The value of the expression is compared with the values of each case.
• If there is a match, the associated block of code is executed.
BMSCE, ISE 31
Example1 for Switch Statement
<!DOCTYPE html>
<html>
<body>
<script>
var grade='B';
var result;
Sample I/O:
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
document.write(result);
</script>
</body> BMSCE, ISE 32
</html>
Example2 for Switch Statement to get the day of the week
<!DOCTYPE html> based on a day number
<html>
<body>
<script>
var day=4;
var dayName;
switch(day) Sample I/O:
{
case 1:dayName='Sunday'; break;
case 2:dayName='Monday'; break;
case 3:dayName='Tuesday'; break;
case 4:dayName='Wednesday'; break;
case 5:dayName='Thursday'; break;
case 6:dayName='Friday'; break;
case 7:dayName='Saturday'; break;
default:
dayName='Invalid day';
}
document.write(dayName);
</script>
</body>
</html>
BMSCE, ISE 33
JavaScript Arithmetic Operators

Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement

BMSCE, ISE 34
Example1 program: // remainder
Arithmetic operators document.write('x % y = ', x % y, '<br />'); // 2

<!DOCTYPE html> // increment


<html> <body> document.write('++x = ', ++x, '<br />'); // x is
<script type="text/javascript"> now 6
{ document.write('x++ = ', x++, '<br />'); // prints
var x = 6; 6 and then increased to 7
var y = 2; document.write('x = ', x, '<br />'); // 7
// addition
document.write('x + y = ', x + y , '<br />'); // 8 // decrement
document.write('--x = ', --x, '<br />'); // x is
// subtraction now 6
document.write('x - y = ', x - y, '<br />'); // 2 document.write('x-- = ', x--, '<br />'); // prints 6
and then decreased to 5
// multiplication document.write('x = ', x, '<br />'); // 5
document.write('x * y = ', x * y, '<br />'); // 15
//exponentiation
// division document.write('x ** y =', x ** y, '<br />');
document.write('x / y = ', x / y, '<br />'); // }
1.6666666666666667
</script>
</body></html>
BMSCE, ISE 35
Sample I/O:

BMSCE, ISE 36
Example2 for Arithmetic Operators
<!DOCTYPE html>
<html> <body><script> Sample I/O:
var a1=40; var b1=25;
//addition
document.writeln('a1+b1 = ', a1+b1,"<br />");
//subtraction
document.writeln('a1-b1 = ', a1-b1,"<br />");
//multiplication
document.writeln('a1*b1 = ', a1*b1,"<br />");
//division
document.writeln('a1/b1 = ', a1/b1,"<br />");
//remainder
document.writeln('a1%b1 = ', a1%b1,"<br />");
//increment
document.writeln('++a1 = ', ++a1,"<br />");// a1 is now 41
document.writeln('a1++ = ',a1++,"<br />");//prints 41 and then increased to 42
document.writeln('a1 = ',a1,"<br />");// 42
//decrement
document.writeln('--a1 = ', --a1,"<br />");// a1 is now 41
document.writeln('a1-- = ',a1--,"<br />");//prints 41 and then decreased to 40
document.writeln('a1 = ',a1,"<br />");// 40
</script> </body></html> BMSCE, ISE 37
JavaScript Assignment Operators
Operator Example Same As
= x=y x=y
+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y

BMSCE, ISE 38
Example program for Assignment operators
<!DOCTYPE html> Sample I/O:
<html>
<head>
<title> Javascript Assignment Operators</title>
</head>
<body>
<h1> Assignment Operations </h1>
<script>
var a = 10, Total = 24;

document.write("Value of the Total = " + (Total += a) + "<br />");


document.write("Value of the Total = " + (Total -= a) + "<br />");
document.write("Value of the Total = " + (Total *= a) + "<br />");
document.write("Value of the Total = " + (Total /= a) + "<br />");
document.write("Value of the Total = " + (Total %= a) + "<br />");
</script>
</body>
</html>

BMSCE, ISE 39
JavaScript Comparison and Logical Operators
Operator Description
== equal to (“4” == 4 returns true)
=== equal value and equal type (“4” === 4
returns false)
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
? ternary operator

BMSCE, ISE 40
Example program1 for Comparison and Logical
operators
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Comparison and Logical Operators </title>
</head>
<body>
<h1>Performing Comparison and logical Operations </h1>
<script>
var a = 32, b = 54;

document.write("Result of " + a +" Greater than " + b +" is = " + (a > b) + "<br />");
document.write("Result of " + a +' Greater than or Equal to ' + b +" is = " + (a >= b) + "<br />");
document.write("Result of " + a +' Less than or Equal to ' + b +" is = " + (a <= b) + "<br />");
document.write("Result of " + a +' Less than ' + b +" is = " + (a < b) + "<br />");
document.write("Result of " + a +' Equal to ' + b +" is = " + (a ==b ) + "<br />");
document.write("Result of " + a +' Not Equal to ' + b +" is = " + (a !=b ) + "<br />");
var i = 0, j=2, k=3, l=8;
document.write(Boolean(i&&j&&k)+ "<br />");
document.write(Boolean(j&&k&&l));
</script>
</body>
</html>
BMSCE, ISE 41
Sample I/O:

BMSCE, ISE 42
Example2 for Comparison and Logical Operators
<!DOCTYPE html>
<html> <body> <script> Sample I/O:
//equal operator
document.write(3 == '3');document.write("<br />");//true
document.write(3 == 3);document.write("<br />");//true
// not equal operator
document.write(3 != 2);document.write("<br />");//true
document.write('wt' != 'WT');document.write("<br />");//true
//strict equal operator
document.write(3 === 3);document.write("<br />");//true
document.write(3 === '3');document.write("<br />");//false
//strict not equal operator
document.write( 3 !== '3');document.write("<br />");//true
document.write( 3 !== 3);document.write("<br />");//false
var x = 5, y = 3;
res = (x < 6) && (y < 5); // true
document.write(res);document.write("<br />");
res = (x < 3) && (y < 5); // false
document.write(res);
</script>
</body>
</html> BMSCE, ISE 43
Loop statements

• for - loops through a block of code a number of times


• for/in - loops through the properties of an object
• while - loops through a block of code while a specified
condition is true
• do/while - also loops through a block of code while a
specified condition is true

BMSCE, ISE 44
The For Loop
Syntax
for (statement 1; statement 2; statement 3) {
code block to be executed
}

Example:
for (i = 0; i < 3; i++) {
document.write("The number is " + i + "<br>”);
}
Output: The number is 0
The number is 1
The number is 2

BMSCE, ISE 45
To display table of numbers from 4 to 16 their squares and cubes
Sample I/O:

<!DOCTYPE html>
<html> <head></head><body>
<script type="text/javascript">
document.write(" <table border=2>
<tr><th>Number</th><th>Squares<
/th> <th>Cubes </th></tr>");
for(i=4;i<17;i++){
document.write("<tr><td>"+ i +
"</td><td>"+(i*i)+"</td><td>"+(i*i
*i)+"</td></tr>");
}
document.write("</table>");
</script>
</body></html>
BMSCE, ISE 46
Javascript to print first 20 Fibonacci numbers:
<!DOCTYPE html>
<html> <head></head><body>
<script type="text/javascript">
var k=0, j=1;
document.write("Javascript script to print first 20 fibonacci numbers <br />");
//document.write(k+" " + j+" ");
for (i=1;i<21;i++)
{
r=k+j;
document.write(r+ " ");
k=j; Sample I/O:
j=r;
}
</script>
</body></html>

BMSCE, ISE 47
The For/In Loop
JavaScript for/in statement loops through the properties of an object.

Example:
<!DOCTYPE html>
<html> <body>
<script type="text/javascript">
var person = {fName:“Vara", LName:“Prasad", age:55};
var x;
for (x in person) {
document.write(person[x]);
}
</script>
</body></html>
Output: VaraPrasad55

BMSCE, ISE 48
The While Loop
• Syntax
while (condition) {
code block to be executed
}

Example:

<!DOCTYPE html>
<html>
<head>
<title>JavaScript While Loop </title>
</head>
<body>
<h1>Example for While Loop </h1> Sample I/O:
<script type="text/javascript">
var i = 0;
while (i < 5) {
document.write("The number is " + i +"<br/>");
i++;
} BMSCE, ISE 49

</script>
The Do/While Loop Output:
• Syntax
do {
code block to be executed
} while (condition);

Example:
<script type="text/javascript">
var i =10;
do {
document.write("The number is " + i+"<br/>");
i++;
} while (i < 20);
</script>
BMSCE, ISE 50
Web Technologies

JavaScript2
(Arrays, Functions)

Mamatha

BMSCE, ISE 51
JavaScript: Arrays

An array is a special variable, which can hold


more than one value at a time.

Storing values in single variables Storing values in arrays


var mobile1=“Samsung”; var mobile = [“Samsung”,
var mobile2=“Motorola”; “Motorola”,”Nokia”];
var mobile3=“Nokia”;

BMSCE, ISE 52
JavaScript Arrays : Array object creation
Can create an array using either
1.An array initializer (array literal) or
2.Array constructor

An array initializer
// an array with 5 elements
var myArray1 = [1,3,5,7,9,”eight”, 6];

Array constructor
// an array with 5 elements
var myArray2 = new Array(1,3,5,7,9, “eight”, 6);
// an empty array of length 100
var myArray3 = new Array(100);
// an empty array of length 0
var myArray4 = new Array();
BMSCE, ISE 53
JavaScript: Arrays
var mobile = [“Samsung”, “Motorola”, ”Nokia”];
OR
var mobile = new Array(“Samsung”, “Motorola”, ”Nokia”);
OR
var mobile = new Array(3);
mobile[0]=“Samsung”; mobile[1]=“Motorola”; mobile[2]=“Nokia”;

L1=mobile.length; //L1 is 3
mobile[3]=“HTC”;
L2=mobile.length; //L2 is 4
//Two dimensional array
var a=[[2,4,6],[1,3,5],[10,20,30]];

BMSCE, ISE 54
Example for JavaScript length property:
<!DOCTYPE html>
<html>
<body> Sample I/O:
<h1>JavaScript Arrays</h1>
<h2>The length Property</h2>

<p>The length property returns the length of an array:</p>

<p id="demo"></p>

<script>
const fruits = ["Banana", "Orange", "Mango"];
let size = fruits.length;
document.getElementById("demo").innerHTML = size;
</script>

</body>
</html>

BMSCE, ISE 55
Example for Array Methods
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE html PUBLIC "-//w3c//DTD XHTML
1.1//EN"

"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd
for (var col = 0; col <=2; col++)
"> document.write(nested_array[row][col],
<!-- nested_arrays.html
" ");
An example illustrate an array of arrays
-->
<html xmlns = "http://www.w3.org/1999/xhtml">
document.write("<br />");
<head> <title> Array of arrays </title> }
</head> // -->
<body> </script>
<script type = "text/javascript"> </body>
<!-- </html>
// Create an array object with three arrays as its
elements
var nested_array = [[2, 4, 6],
[1, 3, 5],
[10, 20, 30]
Sample I/O:
];
// Display the elements of nested_list
for (var row = 0; row <= 2; row++) {
document.write("Row ", row, ": ");

BMSCE, ISE 56
Program:To find the number of negative values, zeros and values
greater than Zeros in the given array
<body> <script type="text/javascript">
var list = [2, 10, -4, 0, 8,-6,0, 21]; Sample I/O:
var i,pos=0,neg=0,zeros=0;
document.write("Elements of Array","<br />");
for(i=0;i<list.length;i++)
document.write(list[i]+" ");
document.write("<br /><br />");
for(i=0;i<list.length;i++) {
if(Number(list[i])>0)
pos++;
else if(Number(list[i])<0)
neg++;
else
zeros++;
}
document.write("Number of Positive Numbers:",pos,"<br / >");
document.write("Number of Negative Numbers: ",neg,"<br / >");
document.write("Number of Zeros: ",zeros,"<br / >");
</script></body>
BMSCE, ISE 57
Program: insertion of an element
Sample I/O:
<script type="text/javascript">
var a = [2, 4, 6,10];
var i, last_index;
document.write("Elements of Array","<br />");
for(i=0;i<a.length;i++)
document.write(a[i]+" ");
document.write("<br /><br />");
var n1=Number(prompt("Enter the number to be inserted: "));
last_index=a.length-1;
while(last_index>=0 && a[last_index] > n1){
a[last_index+1]=a[last_index];
last_index--;
}
a[last_index+1]=n1;
document.write("Elements of the Array after inserting ",n1,"<br />");
for(i=0;i<a.length;i++)
document.write(a[i]+" ");
</script>

BMSCE, ISE 58
Array Methods
var names = new Array[“Mary”,”Murray”,”Murphy”,”Max”]
...
var name_string = names.join(“:”)

join method,
reverse method,
sort method,
slice method,
push method,
pop method,
shift method,
unshift method. . .

BMSCE, ISE 59
JavaScript: Array Methods
INPUT list = [“WP” , ”DS” , “CO” ]
Method Calling the Method OUTPUT

join res=list.join(“:”); list=[WP,DS,CO]


res=WP:DS:CO
sort res=list.sort(); list=[WP,DS,CO]
res=[CO,DS,WP]
concat res=list.concat(“C++”,”DM”); list=[WP,DS,CO]
res=[WP,DS,CO,C++,DM]
reverse res=list.reverse(); list=[WP,DS,CO]
Note: Reversing elements of array res=[CO,DS,WP]
slice res=list.slice(1); list=[WP,DS,CO]
res =[DS,CO]
res=list.slice(-2); list=[WP,DS,CO]
res =[DS,CO]
res=list.slice(1,3); list=[WP,DS,CO,C++]
res =[DS,CO]
res=list.slice(); List=[WP,DS,CO]
BMSCE, ISE 60
res = [WP,DS,CO]
Example for Join:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The Join method</h2>
<p>The Join method helps to join two arrays as a string:</p>
<p id="demo"></p>
<script>
// Original Array
var courses = ["HTML", "CSS", "JavaScript", "React"];
Sample I/O:
// Joining the array elements
document.write(courses.join('|'));
</script>
</body>
</html>

BMSCE, ISE 61
Demo program1 of slice method:
<!DOCTYPE html>
<html>
<body>

<script>
var arr=["AngularJS","Node.js","JQuery","Bootstrap"]
var result=arr.slice(1,3);
document.writeln(result);
</script>
Sample I/O:

</body>
</html>

BMSCE, ISE 62
Demo program2 of slice method:
<!DOCTYPE html>
<html>
<body>
<script>
var arr = [23,56,87,32,75,13];
// Extracted array
var new_arr = arr.slice(2,4);
document.write(arr);
Sample I/O:
document.write("<br>");
document.write(new_arr);
</script>
</body>
</html>

BMSCE, ISE 63
Demo program3 of slice method:
<!DOCTYPE html>
<html>
<body>
<script>
// Extracted array
var arr = [23,56,87,32,75,13];
var new_arr = arr.slice();
document.write(arr,"<br />"); Sample I/O:
document.write(new_arr);
</script>

</body>
</html>
BMSCE, ISE 64
Demo program4 of slice method:
<!DOCTYPE html>
<html>
<body>
<script>
// Extracted array
var arr = [23,56,87,32,75,13];
var new_arr = arr.slice(-3);
document.write(arr,"<br />"); Sample I/O:
document.write(new_arr);
</script>

</body>
</html>
BMSCE, ISE 65
Demo program5 of slice method:
<!DOCTYPE html>
<html>
<body>
<script>
// Extracted array
var arr = [23,56,87,32,75,13];
var new_arr = arr.slice(2);
document.write(arr,"<br />"); Sample I/O:
document.write(new_arr);
</script>

</body>
</html>
BMSCE, ISE 66
JavaScript Slice method example:
<!DOCTYPE html>
<html><body>
<h1>JavaScript Arrays</h1>
<h2>The Slice method</h2>
<p>The slice() method returns a new array containing a portion of the original array, based
on the start and end index provided as arguments:</p>
<p id="demo"></p>
<script>
// Original Array
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Case 1: Extract the first 3 elements of the array
const case1 = arr.slice(0, 3);
document.write("Case 1: First 3 Array Elements: ", case1 ,"<br />");
// Case 2: Extract the last 3 array elements
const case2 = arr.slice(-3);
document.write("Case 2: Last 3 Array Elements: ", case2,"<br />");
// Case 3: Extract elements from middle of array
const case3 = arr.slice(3, 7);
document.write("Case 3: Extract elements from middle: ", case3,"<br />");

BMSCE, ISE 67
// Case 4: Start index is greater than end index
const case4 = arr.slice(5, 2);
document.write("Case 4: Start index is greater than end index: ",
case4,"<br />");
// Case 9: Start and end index are
negative
// Case 5: Negative start index // and out of range
const case5 = arr.slice(-4, 9); const case9 = arr.slice(-15, -10);
document.write("Case 5: Negative start index: ", case5,"<br />"); document.write("Case 9: Start and
end index are negative"
// Case 6: Negative end index
+ " and out of range: ", case9);
const case6 = arr.slice(3, -2);
document.write("Case 6: Negative end index: ", case6,"<br />");
</script>
// Case 7: Only start index is provided </body>
const case7 = arr.slice(5); </html>
document.write("Case 7: Only start index is provided: ", case7,"<br />");

// Case 8: Start index and end index are out of range


const case8 = arr.slice(15, 20);
document.write("Case 8: Start and end index out of range: ", case8,"<br
/>");

BMSCE, ISE 68
Sample I/O:

BMSCE, ISE 69
JavaScript: Array Methods
Method Calling the Method OUTPUT
push list = [“WP” , ”DS” , “CO” ] res=4
res=list.push(“C++”); list=[“WP”,”DS”,”CO”,”C++”]
pop list = [“WP” , ”DS” , “CO” ] res=“CO”
res=list.pop(); list=[“WP”, “DS”]
Unshift list = [“WP” , ”DS” , “CO” ] res =4
(add) res=list.unshift(“C++”); list=[“C++”, “WP”,”DS”,”CO”]

Shift list = [“WP” , ”DS” , “CO” ] res=“WP”


(remove res=list.shift(); list=[“DS”,”CO”]
from
queue)

BMSCE, ISE 70
Push method example:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>
<h2>The Push method</h2>
<p>The Push method is used to add one or more elements to the end of an array:</p>
<p id="demo"></p>
<script>
var languages = ["JavaScript", "Python", "Java", "Lua"];

var count = languages.push("C++");


document.write(languages,"<br />"); // [ 'JavaScript', 'Python', 'Java', 'Lua', 'C++' ]
Sample I/O:
</script>
</body>
</html>

BMSCE, ISE 71
JavaScript Functions
General Syntax
function Name(parameter1, parameter2)
{
//function code
}

BMSCE, ISE 72
JavaScript Functions
<html> <head></head>
<body>
<script type="text/javascript">
var a,b,c;
a=10; b=20;

//actual parameters a and b


c=sum(a,b);
document.write("Total :",c);

//formal parameters x and y


function sum(x,y)
{
var z=x+y;
return z;
}
</script>
</body></html>
BMSCE, ISE 73
Parameters

<!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN"


"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<!-- parameters.html
The params function and a test driver for it.
This example illustrates function parameters
-->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head> <title> Parameters </title>
<script type = "text/javascript">
<!--
// Function params
// Parameters: two named parameters and one unnamed
// parameter, all numbers
// Returns: nothing

BMSCE, ISE 74
function params(a, b) {
document.write("Function params was passed ",
arguments.length, " parameter(s) <br />");
document.write("Parameter values are: <br />");

for (var arg = 0; arg < arguments.length; arg++)


document.write(arguments[arg], "<br />");

document.write("<br />");
}
// -->
</script>
</head>

BMSCE, ISE 75
<body>
<script type = "text/javascript">
// A text driver for params

params("Mozart");
params("Mozart", "Beethoven");
params("Mozart", "Beethoven", "Tchaikowsky");
</script>
</body>
</html>

BMSCE, ISE 76
Sample I/O:

BMSCE, ISE 77
Example:

<!DOCTYPE html>
<!-- medians.html
A function and a function tester
Illustrates array operations
-->
<html>
<head> <title> Median Computation </title>
<script type = "text/javascript">
<!--
/* Function median
Parameter: An array of numbers
Result: The median of the array
Return value: none
*/

BMSCE, ISE 78
function median(list) {
list.sort(function (a, b) {return a - b;});

var list_len = list.length;

// Use the modulus operator to determine whether


// the array's length is odd or even
// Use Math.floor to truncate numbers
// Use Math.round to round numbers

if ((list_len % 2) == 1)
return list[Math.floor(list_len / 2)];
else
return Math.round((list[list_len / 2 - 1] + list[list_len / 2]) / 2);
} // end of function median
// -->
</script>
</head>

BMSCE, ISE 79
<body>
<script type = "text/javascript">
<!--
var my_list_1 = [8, 3, 9, 1, 4, 7];
var my_list_2 = [10, -2, 0, 5, 3, 1, 7];
var med = median(my_list_1);
document.write("Median of [", my_list_1, "] is: ", med,"<br />");
med = median(my_list_2);
document.write("Median of [", my_list_2, "] is: ", med, "<br />");
// -->
</script>
</body>
Sample I/O:
</html>

BMSCE, ISE 80
Test Your Knowledge

• Add FOR LOOP to the following program that output the


numbers 1 3 5 7 9 with line breaks between each number.
<!DOCTYPE html>
<html>
<body>
<script>
var i;
// add for loop here
</script>
</body>
</html>

BMSCE, ISE 81
Test Your Knowledge: Answer

• Add FOR LOOP to the following program that output the numbers 1 3 5 7
9 with line breaks between each number.
<!DOCTYPE html>
<html> <head></head><body>
<script>
var i;
for(i=1;i<10;i=i+2)
document.write(i,"<br/>");
</script>
</body>
</html>

BMSCE, ISE 82
Test Your Knowledge
• Try to fix the following code to output 0 1 2 3 4
<!DOCTYPE html>
<html> <head></head> <body>
<script>
var i = 0;
do {
document.write( );
i= ;
}while ( );
</script>
</body></html>

BMSCE, ISE 83
Test Your Knowledge:Answer

• Try to fix the following code to output 0 1 2 3 4


<!DOCTYPE html>
<html> <head></head> <body>
<script>
var i = 0;
do {
document.write(i+" " );
i= i+1 ;
}while ( i<5 );
</script>
</body></html>

BMSCE, ISE 84
Find the output of the following program:

<!DOCTYPE html>
<html> <head></head>
<body>
<script type="text/javascript">
var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango”,
"Chikko"];
var citrus = fruits.slice(1, 3);
document.write(citrus+"</br>");
citrus = fruits.slice(1);
document.write(citrus+"</br>");
citrus = fruits.slice(-2);
document.write(citrus+"</br>");
</script>
</body>
</html>

BMSCE, ISE 85
Answer
<!DOCTYPE html>
<html> <head></head>
<body>
<script type= "text/javascript">
var fruits =
["Banana","Orange","Lemon","Apple","Mango","Chikko"];

var citrus = fruits.slice(1, 3);


document.write(citrus+"</br>");
citrus = fruits.slice(1);
document.write(citrus+"</br>");
citrus = fruits.slice(-2);
document.write(citrus+"</br>");
</script>
</body>
</html>
BMSCE, ISE 86
Test Your Knowledge

Write JavaScript function which accepts an array of names, represented as strings


and returns number of names in the given array that end with either ‘ie’ or ‘y’
Example:
Input list = [“Harish Gowda", "Mary GracIe", "Sandeep Varma", "Archana Reddy"];

Output: 2

BMSCE, ISE 87
Solution
<html> <head></head ><body> <script type="text/javascript">
function find(names) {
var count = 0, tmp, pattern1, pattern2;
while(names.length)
{
tmp = names.shift();
Sample I/O:
pattern1 = tmp.toLowerCase().slice(-2);
pattern2 = tmp.toLowerCase().slice(-1);
if( pattern1 =="ie" || pattern2 =="y" )
count++;
}
return count;
}
var list = ["Harish Gowda","Mary Gracie","Sandeep Varma","Archana Reddy"];
var count; count=find(list);
document.write("<br />",count, " names end with either 'ie' or 'y'");
document.write("<br />", list);
</script> </body></html> BMSCE, ISE 88
Test Your Knowledge
Write JavaScript function which accepts input from user a string and
prints the position of the leftmost vowel.

BMSCE, ISE 89
Solution
<html> <head></head ><body> <script type="text/javascript">
//function to print the position of the leftmost vowel in the string
function firstvowel(){
var find = 0,pos,i; var str=prompt("Enter the string: ");
str=str.toLowerCase();
for(i=0;i<str.length;i++)
{
if(str[i]=='a' || str[i]=='e' || str[i]=='i' || str[i]=='o' || str[i]=='u')
{
find=1; pos=i; break;
}
}
if(find)
document.write("Position of first vowel in the string ", str, " was ",(pos+1));
else
document.write("Vowel Not found");
return;
}
document.write("Function to find first vowel in a String","<br />");
firstvowel(); </script> </body> </html>
BMSCE, ISE 90
Sample I/O:

BMSCE, ISE 91
Question: Find the output generated by this program
<!DOCTYPE html> <html> <head></head>
<body>
<script type="text/javascript">
document.write("BMS College of Engineering, Bangalore");
alert("Welcome to BMSCE");
var registration=confirm("Do You want to register for 4th Sem ?");
if(registration){
name=prompt("Enter your name:");
if(name==“Manjunatha")
alert("Hello Manjunatha");
else
alert("You are not Manjunatha");
}
else
alert("Please Register later");
</script>
</body>
</html>

BMSCE, ISE 92
Sample I/O:

BMSCE, ISE 93
Characteristics of Array objects:
• Length of an array is both read and write accessible through the ‘length’
property, which is created for every array object by the Array constructor.
• Lowest index of every array is zero.

Example program:
<!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns = "http://www.w3.org/1999/xhtml">


<head> <title> Name list </title>
</head>
<body>
<script type = "text/javascript">
<!--
// The original list of names
var name_list = new Array("A1","Betty","Kasper",
"Michael", "Roberto", "Zimbo");
var new_name, index, last;
BMSCE, ISE 94
// Insert the new name into its spot in the
// Loop to get a new name and array
insert it name_list[last + 1] = new_name;
while (new_name =
prompt("Please type a new // Display the new array
name", "")) { document.write("<p><b>The new
name list is:</b> ",
// Loop to find the place for the "<br />");
new name for (index = 0; index <
last = name_list.length - 1; name_list.length; index++)
document.write(name_list[index],
"<br />");
while (last >= 0 && document.write("</p>");
name_list[last] > new_name) { } //** end of the outer while loop
// -->
name_list[last + 1] = </script>
name_list[last]; </body>
last--; </html>
}

BMSCE, ISE 95
Sample I/O:

BMSCE, ISE 96
Exercises:

1. JavaScript to find reverse of a number


2. Words of input text are printed in alphabetical
orders
3. Function: no_zeros
Parameter: An array of numbers
Returns: true if the given array included zero
values, false otherwise
4. Function:first_vowel
Parameter: A string
Returns: the position in the string of the
leftmost vowel

BMSCE, ISE 97
Web Technologies

JavaScript2
(Pattern Matching Using Regular Expressions)

Mamatha

20 April 2025 ISE, BMSCE 1


Pattern Matching Using Regular Expressions

• What is Pattern ?
• Some specific substring in a given string
• Example: Strings having atleast one occurrence of two consecutive letter a: baacd,
dcbaaba, aabdc, cbdaa
• What is Regular Expression ?
• Expressing the general PATTERN format in short hand notation
• A regular expression is a sequence of characters that forms a search pattern.
• Example: Regular expression /aa/ identifies the pattern for occurrence of two
consecutive letter a

20 April 2025 ISE, BMSCE 2


Pattern Matching Method: Search
• Search method takes pattern as parameter
• Patterns sent as parameter are delimited with slashes ( / / )
• Search method returns the position in the string where the pattern is matched. If
there is no match, Search method returns -1.
• General Syntax: /pattern/modifier

Example Pattern Description


/aa/ Two consecutive small letter a
/aa/i Two consecutive small or capital letter a
/a{4}/i Four consecutive small or capital letter a

20 April 2025 ISE, BMSCE 3


Character and Character-Class pattern
Modifier Description
i Perform case-insensitive matching
g Perform a global match (find all matches rather than
stopping after the first match)
m Perform multiline matching

20 April 2025 ISE, BMSCE 4


Example: Program to identify two consecutive a
occurrence in the given string.
<!DOCTYPE html> <html> <body>
<script type="text/javascript"> Sample I/O:
var MainString="dcaaba";
var index;
index=MainString.search(/aa/);
if(index== -1)
{
alert("MainString Doesnot contain two consecutive a's");
}
else{
alert("MainString contain two consecutive a's and it is found at the position"+index);
}
</script>
</body></html>

20 April 2025 ISE, BMSCE 5


Example: Program to identify two consecutive a
occurrence in the given string.
<!DOCTYPE html> <html> <body> Sample I/O:
<script type="text/javascript">
var MainString="dcabac";
var index;
index=MainString.search(/aa/);
if(index== -1)
{
alert("MainString Doesnot contain two consecutive a's");
}
else{
alert("MainString contain two consecutive a's and it is found at the position"+index);
}
</script>
</body></html>
20 April 2025 ISE, BMSCE 6
Example
<!DOCTYPE html> <html> <body>

<script type="text/javascript"> Sample I/O:


var MainString="dcaabac";
var index;
index=MainString.search(/AA/);
if(index== -1)
{
alert("MainString Doesnot contain two consecutive A's");
}
else{
alert("MainString contain two consecutive a's and it is found at the position"+index);
}
</script>
</body></html>

20 April 2025 ISE, BMSCE 7


Example
<!DOCTYPE html> <html> <body>

<script type="text/javascript"> Sample I/O:


var MainString="dcAAba";
var index;
index=MainString.search(/AA/);
if(index== -1)
{
alert("MainString Doesnot contain two consecutive A's");
}
else{
alert("MainString contain two consecutive A's and it is found at the position"+index);
}
</script>
</body></html>

20 April 2025 ISE, BMSCE 8


Example
<!DOCTYPE html> <html> <body> Sample I/O:
<script type="text/javascript">
var MainString="dcAAba";
var index;
index=MainString.search(/aa/i);
if(index== -1)
{
alert("MainString Doesnot contain two consecutive a's");
}
else{
alert("MainString contain two consecutive a's and it is found at the position"+index);
}
</script>
</body></html>
20 April 2025 ISE, BMSCE 9
Example
<!DOCTYPE html>
Sample I/O:
<html><body>
<script type="text/javascript">
var str = "bms6colle8ge";
var patt1 = /[0-9]/;
var result = str.search(patt1);
if(result==-1)
document.write("Digit does not exist in the given string");
else
document.write("Atleast one digit exists in the given string");
</script>
</body></html>

20 April 2025 ISE, BMSCE 10


Question: Find the output of the program
<!DOCTYPE html>
<html><body> Sample I/O:
<script type="text/javascript">
var str = "bms6colle8ge";
var patt1 = /[1-4]/;
var result = str.search(patt1);
if(result==-1)
document.write("Digit does not exist in the given string");
else
document.write("Atleast one digit exists in the given string");
</script>
</body></html>

20 April 2025 ISE, BMSCE 11


Question: Find the output of the program
<!DOCTYPE html>
<html><body>
Sample I/O:
<script type="text/javascript">
var str = "bms6c0123456789olle8ge";
var patt1 = /0123456789/;
var result = str.search(patt1);
if(result==-1)
document.write("Digit does not exist in the given string");
else
document.write("Atleast one digit exists in the given string");
</script>
</body></html>

20 April 2025 ISE, BMSCE 12


Question: Find the output of the program
<!DOCTYPE html>
<html><body>
Sample I/O:
<script type="text/javascript">
var str = "bms6colle8ge";
var patt1 = /0123456789/;
var result = str.search(patt1);
if(result==-1)
document.write("pattern does not exist in the given string");
else
document.write("Atleast one digit exists in the given string");
</script>
</body></html>

20 April 2025 ISE, BMSCE 13


JavaScript String match() Method
The match() method searches a string for a match against a regular expression and returns the matches, as an
Array object

Code Output

<script type="text/javascript">
var str = "The rain in Bangalore stays mainly in the plain";
var result = str.match(/ain/);
document.write(result);
</script>

20 April 2025 ISE, BMSCE 14


Example for string match method:
Sample I/O:
<!DOCTYPE html>
<html>
<body>
<script>
var str="Javapoint";
document.writeln(str.match("Java"));
</script>
</body>
</html>
JavaScript String match() Method
The match() method searches a string for a match against a regular expression, and returns the matches, as an
Array object
Code Output

<script type="text/javascript"> Ain


var str = "The rain in Bangalore stays mainly in the plain";
var result = str.match(/ain/);
document.write(result);
</script>

<!DOCTYPE html>
<html>
<body>
<script>
var str= "The rain in Bangalore stays mainly in the plain";
document.writeln(str.match(/ain/g));
</script>
</body> g Perform a global match (find all matches rather than stopping after the first match)
</html>

20 April 2025 ISE, BMSCE 16


Predefined character classes

Name Equivalent Pattern Matches


\d [0-9] A digit
\D [^0-9] Not a digit
\w [A-ZA-Z_0-9] A word character (alphanumeric)
\W [^A-ZA-Z_0-9] Not a word character
\s [ \r\t\n\f] A white-space character
\S [^ \r\t\n\f] Not a white-space character

Note: ^ is circumflex
Example
Name Equivalent Pattern Matches
\d [0-9] A digit
\D [^0-9] Not a digit

<html> <body> 1,0,0


<script type="text/javascript">
var str = "Give _ 100%! try";
var patt1 = /\d/g;
var result = str.match(patt1);
document.write(result);
</script>
</body> </html>
<script type="text/javascript"> G,i,v,e, ,_, ,%,!, ,t,r,y
var str = "Give _ 100%! try";
var patt1 = /\D/g;
var result = str.match(patt1);
document.write(result);
</script>
20 April 2025 ISE, BMSCE 18
Example

\w [A-Za-z_0-9] A word character (alphanumeric)


\W [^A-Za-z_0-9] Not a word character

<script type="text/javascript"> G,i,v,e,_,1,0,0,t,r,y


var str = "Give _ 100%! try";
var patt1 = /\w/g;
var result = str.match(patt1);
document.write(result);
</script>
<script type="text/javascript"> ,%,!,
var str = "Give _ 100%! try";
var patt1 = /\W/g;
var result = str.match(patt1);
document.write(result);
</script>
20 April 2025 ISE, BMSCE 19
Example

\s [ \r\t\n\f] A whitespace character


\S [^ \r\t\n\f] Not a whitespace character

<script type="text/javascript"> ,,,


var str = "Give _ 100%! try";
var patt1 = /\s/g;
var result = str.match(patt1);
document.write(result);
</script>
<script type="text/javascript"> G,i,v,e,_,1,0,0,%,!,t,r,y
var str = "Give _ 100%! try";
var patt1 = /\S/g;
var result = str.match(patt1);
document.write(result);
</script>

20 April 2025 ISE, BMSCE 20


Example
Pattern Description
/\d\.\d\d/ Matches a digit, followed by period, followed by
two digits
/\D\d\D/ Matches single digit
/\w\w\w/ Matches three adjacent word characters
or
/\w{3}/

20 April 2025 ISE, BMSCE 21


Question: Find the Output

20 April 2025 ISE, BMSCE 22


Example

<script type="text/javascript"> ,t,h, ,a,l,l, ,t,h,e,r,e, ,?


var str = "Is this all there is?";
var patt1 = /[^is]/gi;
var result = str.match(patt1);
document.write(result);
</script>
<script type="text/javascript"> b,5,M,6,7,s,8,9
var str = "1b253M67s894";
var patt1 = /[^1-4]/g;
var result = str.match(patt1);
document.write(result);
</script>

<script type="text/javascript"> b
var str = "1b253M67s894";
var patt1 = /[^1-4]/;
var result = str.match(patt1);
document.write(result);
</script>

20 April 2025 ISE, BMSCE 23


Example

20 April 2025 ISE, BMSCE 24


Character and Character-Class pattern

Quantifier Description

n+ Matches any string that contains at least one n

n* Matches any string that contains zero or more occurrences of n

n? Matches any string that contains zero or one occurrences of n

. Find a single character, except newline or line terminator

Pattern Description

/x*y+z?/ Matches the strings that begin with any number of x’s (including
zero), followed by one or more y’s, possibly followed by z
/\d+\.\d*/ Matches one or more digits followed by decimal point and
possibly more digits

20 April 2025 ISE, BMSCE 25


Example
Quantifier Description

n+ Matches any string that contains at least one n

<script type="text/javascript"> ooo


var str = "Hellooo World! Hello W3Schools!";
var patt1 = /o+/;
var result = str.match(patt1);
document.write(result);
</script>
<script type="text/javascript"> ooo,o,o,oo
var str = "Hellooo World! Hello W3Schools!";
var patt1 = /o+/g;
var result = str.match(patt1);
document.write(result);
</script>

20 April 2025 ISE, BMSCE 26


Example
n* Matches any string that contains zero or more occurrences of n

<script type="text/javascript"> l
var str = "Hellooo World! Hello W3Schools!";
var patt1 = /lo*/;
var result = str.match(patt1);
document.write(result);
</script>
<script type="text/javascript"> l,looo,l,l,lo,l
var str = "Hellooo World! Hello W3Schools!";
var patt1 = /lo*/g;
var result = str.match(patt1);
document.write(result);
</script>

20 April 2025 ISE, BMSCE 27


Example
n? Matches any string that contains zero or one occurrences of n

<script type="text/javascript"> 1
var str = "1, 100 or 1000?";
var patt1 = /10?/;
var result = str.match(patt1);
document.write(result);
</script>
<script type="text/javascript"> 1,10,10
var str = "1, 100 or 1000?";
var patt1 = /10?/g;
var result = str.match(patt1);
document.write(result);
</script>

20 April 2025 ISE, BMSCE 28


Character and Character-Class pattern
Anchors Description
^ at the beginning of a pattern, matches the
beginning of a string
$ at the end of a pattern, matches the end of a string

Pattern Description

/^HTML/ Matches HTML coding is exciting


But does not match I am excited by HTML
/HTML$/ Does not match HTML coding is exciting
But matches I am excited by HTML

20 April 2025 ISE, BMSCE 29


Characters and Character class patterns:
A period matches any character except newline.
Eg: /snow./ pattern matches “snowy”,”snowe”,”snowd”
To match a period in a string, period must be preceded by a backslash.
Eg: /3.\.4/ matches 3.4
Pattern /3.4/ matches 3.4 and 374
Character classes: used to specify classes of characters rather than individual characters.
Pattern [abc] matches ‘a’, ‘b’ or ‘c’
pattern [^aeiou] matches any characters except the letters ‘a’,’e’,’I’,’o’, and ‘u’
Pattern /\d.\d\d/ matches a digit, followed by a period, followed by two digits
/\D\d\D/ matches a single digit
/\w\w\w/ matches three adjacent word characters
/xy{4}z/ matches xyyyyz
Quantifiers: *, + , ?:
/x*y+z/ matches any number of x, followed by one or more y’s, possibly followed by z
/\d+\.\d*/ matches a string of one or more digits followed by a decimal point and possibly more digits
/[A-Za-z\w*/ matches the identifiers in some programming languages
/\bis\b/ matches “A tulip is a flower” but not “A frog isn’t” where \b is boundary which matches the boundary position between a word
character(\w) and a non-word character(\W) in either order.
Boundary pattern matches a position between two characters.
Write a Regular Expression to identify the
strings ending with either ‘ie’ or ‘y’
Note: Should work for case insensitive

20 April 2025 ISE, BMSCE 31


Solution
<html><body><script type="text/javascript"> if(tmp.toLowerCase().search(/(ie|y)$/)!=-1)
//Accept array list of names, return number of names in array that end with either ie
or y
count++;
}
function find(names) { return count;
var count = 0; }
var list = ["Dinesh Gowda", "Mary GracIe", "Sandeep
var tmp, pattern1, pattern2; Sharma", "Archana Reddy"];
while(names.length){ var i, count;
tmp = names.shift(); document.write("List of Names: ","<br />");
for(i=0;i<list.length;i++)
/* pattern1 = tmp.toLowerCase().slice(-2);
document.write(list[i], "<br />");
pattern2 = tmp.toLowerCase().slice(-1); count=find(list);
document.write("<br />",count, " names end with
if( pattern1 =="ie" || pattern2 =="y" )
either 'ie' or 'y'");
count++; document.write("<br />", list);
*/ </script> </body></html>

20 April 2025 ISE, BMSCE 32


Write JavaScript function which accepts input from user a string and
prints the position of the leftmost vowel. Use regular expression.

20 April 2025 ISE, BMSCE 33


Solution: Without using Regular expression
<html> <body> <script type="text/javascript">
//function to print the position of the leftmost vowel in the string
function firstvowel(){
var find = 0,pos,i;
Input is mamatha
var str=prompt("Enter the string: ");
str=str.toLowerCase();
for(i=0;i<str.length;i++)
{
if(str[i]=='a' || str[i]=='e' || str[i]=='i' || str[i]=='o' || str[i]=='u')
{ find=1; pos=i; break; }
}
if(find)
document.write("Position of first vowel in the string ", str, " was ",(pos+1));
else
document.write("Vowel Not found");
return;
}
document.write("Function to find first vowel in a String","<br />");
firstvowel();
</script> </body> </html>

20 April 2025 ISE, BMSCE 34


Answer
<html> <body> <script type="text/javascript">
//function to print the position of the leftmost vowel in the string
function firstvowel(){
Input is mamatha
var pos;
var str=prompt("Enter the string: ");
pos=str.search(/[aeiou]/i)
if(pos==-1)
document.write("Vowel Not found");
else
{
document.write("Position of first vowel in the string is: ", (pos+1));
}
}
document.write("Function to find first vowel in a String","<br />");
firstvowel();
</script> </body> </html>

20 April 2025 ISE, BMSCE 35


How we can modify this program to print the all vowel characters found?

<html> <body> <script type="text/javascript">

//function to print the position of the leftmost vowel in the string


function firstvowel(){
var pos;
var str=prompt("Enter the string: "); Enter String: bmscollege
pos=str.search(/[aeiou]/i)
if(pos==-1)
document.write("Vowel Not found");
else
{
document.write("Position of first vowel in the string is: ", (pos+1));
}
}
document.write("Function to find first vowel in a String","<br />");
firstvowel();
</script> </body> </html>

20 April 2025 ISE, BMSCE 36


Answer
<html> <body> <script type="text/javascript">
//function to print the position of the leftmost vowel in the string
function firstvowel(){
var pos,vowel;
var str=prompt("Enter the string: ");
pos=str.search(/[aeiou]/i) Sample I/O:
vowel = str.search(/[aeiou]/gi)
if(pos==-1)
document.write("Vowel Not found");
else
{
document.write("Position of first vowel in the string is: ", (pos+1),"<br />");
document.write("Vowels found was:",vowel);
}
}
document.write("Function to find first vowel in a String","<br />");
firstvowel();
</script> </body> </html>

20 April 2025 ISE, BMSCE 37


Other Pattern Matching Methods
• The replace method takes a pattern parameter and a string parameter
• The method replaces a match of the pattern in the target string with the second parameter
• A g modifier on the pattern causes multiple replacements
Example:
var str = "BMS college of Engineering";
var new_str = str.replace(/college/,"Institute");
document.write(str,"<br />",new_str);

Output:
BMS college of Engineering
BMS Institute of Engineering

20 April 2025 ISE, BMSCE 38


Question: Find the Output
Input Output
<script type="text/javascript"> Mr Blue has a red
house and a blue car.
var str = "Mr Blue has a blue house and a
blue car.";
var result = str.replace(/blue/, "red");
document.write(result);
</script>
<script type="text/javascript"> Mr Blue has a
var str = "Mr Blue has a blue house and a red house and
blue car."; a red car.
var result = str.replace(/blue/g, "red");
document.write(result);
</script>
20 April 2025 ISE, BMSCE 39
Other Pattern Matching Methods
• The split method splits the object string using the pattern to specify the split points

Example:
var str="BMS:RV:PES";
var colleges=str.split(":");
document.write("<br />", str,"<br />",colleges);

Output:
BMS:RV:PES
BMS,RV,PES

20 April 2025 ISE, BMSCE 40


Question: Find the Output
Input Output
<script type="text/javascript"> How,are,youpreparing,for
,Test-1?
var str = "How are youpreparing for Test-1?";
var res = str.split(" ");
document.write(res);
</script>
<script type="text/javascript">
var str = "How are you preparing for Test-1?";
var res = str.split("");
document.write(res);
</script>

20 April 2025 ISE, BMSCE 41


Other Pattern Matching Methods
• The match method takes one pattern parameter
• Without a g modifier, the return is an array of the match and parameterized sub-matches
• With a g modifier, the return is an array of all matches

Example:
var str = "BMS college of Engineering";
var matches=str.match(/college/);
document.write("<br />", str,"<br />",matches);

Output:
BMS college of Engineering
college
20 April 2025 ISE, BMSCE 42
Write a program check validity of the USN of the format 1BM19IS followed by three digits.
Example:
Valid: 1BM19IS065, 1bm19is999
Not Valid: 1BM18IS6 , 1BM17IS038, 1is16BM065
Note: Accept the USN from the user through textbox.

20 April 2025 ISE, BMSCE 43


Answer
<body>
<html> <form name="strForm" onsubmit="validate();">
<head> <label> <b> Enter USN </b> </label>
<input type="text" name="str"/>
<script type="text/javascript">
<input type="submit" value="Submit"/>
function validate() { </form>
strValidate=strForm.str.value.search(/1BM19IS[0-9]{3}/i); </body>
</html>
if(strValidate== -1) {
alert("Not Valid");
} else
alert("Valid"); }
</script> </head>

20 April 2025 ISE, BMSCE 44


Write a Regular Expression to validate ten digit mobile number
Example:
Valid: 8762742909, 9448444160
Not Valid: 84441604, 762742909

20 April 2025 ISE, BMSCE 45


Answer
<html>
<body>
<head> <form name="strForm" onsubmit="validate();">
<script type="text/javascript"> <label> <b> Enter Mobile Number </b> </label>
function validate() { <input type="text" name="str"/>
<input type="submit" value="Submit"/>
strValidate=strForm.str.value.search(/[0-9]{10}/); </form>
if(strValidate== -1) { </body>
alert("Not Valid"); </html>
}
alert("Valid");
}
</script>
</head>

20 April 2025 ISE, BMSCE 46


Exercise1:

• Write a program using JavaScript to accept a value in the variable with name time. If time value is
less than 10, display "Good morning" message, if time value is less than 18 display "Good day"
message, otherwise a "Good evening".
• Show the implementation using both If-else statement and also using switch statement

BMSCE, ISE 47
Exercise2:
Write Javascript program to insert the numbers into the existing
array which maintains sorting order.
Example: If the input array a=[2,4,6,10] then after inserting 1 and 8
the same array should be modified to contain a=[1,2,4,6,8,10].
Note: Should not use any temporary array.

BMSCE, ISE 48
Exercise3:
JavaScript program to remove all Zeros in the given array
Example INPUT list = [2, 0, 0, 4]
OUTPUT list = [2,4]

BMSCE, ISE 49
Exercise4:Which of the following solution is Better ?
Solution 1 last=a.pop();
a.pop(); a.pop();a.push(last);
Solution 2 for(i=0; i < a.length ; i++)
Write JS program to remove {
all Zeros in the given array. tmp = a[i];
Example: if( tmp !== 0 )
INPUT a = [2, 0, 0, 4] {
OUTPUT a = [2,4] new_list.push(tmp);
}
}
a=new_list;
Solution 3 j=0;
for(i=0; i<a.length; i++ )
{
if (a[i] != 0)
a[j++] = a[i];
}
a.length=j;
BMSCE, ISE 50
Exercise5:
1. Write javaScript code to reverse a given number.
2. Write javaScript code to find median of the given array of
elements
3. Write javaScript code to find the average of each row in a given
matrix.
4. Write HTML files and JavaScript scripts for input of
line of text using prompt. Generate the output as the
words of the input text in alphabetical order.
5. Write a java script code to print the number with its
digits in reverse order.

BMSCE, ISE 51
Exercises:
1. JavaScript to find reverse of a number
<!DOCTYPE html> while (n>0)
<html> {
<head> rem = n % 10;
<title>JavaScript to Reverse a number rev = rev * 10 + rem ;
</title> n = Math.floor(n/10);
</head> }
document.write("The given number is : "
<body> +num+ " <br/> The reversed number is : "
<h1>Reverse a number </h1> +rev+ "\n");
<script type ="text/javascript"> </script>
var num = prompt("Enter the number to </body>
be reveresed :", " "); </html>
var n= num;
var rev = 0, rem;

BMSCE, ISE 52
Sample I/O:

BMSCE, ISE 53
Exercises:2. Words of input text are printed in
alphabetical orders
<!DOCTYPE html>
<html>
<head>
document.write("Given input is :
<title>JavaScript to print words of the input text, in "+words+"<br />");
alphabetical order </title>
// Sorting the input array using array.sort
</head>
<body>
const sortedWords = words.sort();
<h1>Print words of the input text, in alphabetical order
</h1>
//Getting the sorter array output
<script type ="text/javascript">
document.write("Sorted words are :
const words = [
"JavaScript",
"+sortedWords);
"Program", </script>
"to", </body>
"Sort", </html>
"Words",
"in",
"Alphabetical",
"Order",
];

BMSCE, ISE 54
Sample I/O:

BMSCE, ISE 55
Output: A table of numbers from 5 to 15 and their squares and cubes.
<!DOCTYPE html>
<html lang = "en">
<head>
<title> Exercise 4.1 modified </title>
<meta charset = "utf-8" />
</head> <body>
<script type = "text/javascript">
<!--
var number, square, cube;
document.write("Number, Square, Cube <br /><br />");
for (number = 5; number < 16; number++) {
square = number * number;
cube = number * square;
document.write(number + ", " + square + ", " +
cube + "<br />");
}
// -->
</script></body>
</html>

BMSCE, ISE 56
Sample I/O:

BMSCE, ISE 57
Exercise 4.1:Output: A table of numbers from 5 to 15 and
their squares and cubes, using alert.
<html> <head>
<script type = "text/javascript">
<!--
function alertTable() {
var result = "";
for (var i = 5; i <= 15; i++) {
result += i + " " + i*i + " " + i*i*i + "\n";
}
alert(result);
}
</script>
</head ><body> <script type="text/javascript">
alertTable()
</script> </body></html>
BMSCE, ISE 58
Sample I/O:

BMSCE, ISE 59
Exercise 4.2: Output: The first 20 Fibonacci numbers, which are defined as in
the sequence 1,1,2,3,. . .
<!DOCTYPE html>
<html lang = "en">
<head>
<title> Exercise 4.2 </title>
<meta charset = "utf-8" />
</head>
<body>
<script type = "text/javascript">
<!--
var first = 1, second = 1, next, count;
document.write("First 20 Fibonacci Numbers <br/><br/>");
document.write("1 - 1 <br/> 2 - 1 <br/>");
for (count = 3; count <= 20; count++) {
next = first + second;
document.write(count + " - " + next + "<br/>");
first = second;
second = next;
}
// -->
</script></body></html>

BMSCE, ISE 60
Sample I/O:

BMSCE, ISE 61
Exercise 4.4: Modify exercise 4.2 to use prompt to input a number n that is
the number of the Fibonacci number required as output.
<!DOCTYPE html>
<html lang = "en">
<head>
<title> Exercise 4.4 </title>
<meta charset = "utf-8" />
</head>
<body>
<script type = "text/javascript">
var first = 1, second = 1, next, count;
number = prompt("How many Fibonacci numbers do you want? (3-50)", "");
if (number >= 3 && number <= 50) {
document.write("First " + number + " Fibonacci Numbers <br /><br />");
document.write("1 - 1 <br/> 2 - 1 <br />");
for (count = 3; count <= number; count++) {
next = first + second;
document.write(count + " - " + next + "<br />");
first = second; second = next;
}
}
else
document.write("Error - number not in the range 3-50");
</script></body></html>
BMSCE, ISE 62
Sample I/O:

BMSCE, ISE 63
Exercise 4.6:
Input: A line of text, using prompt
Output: The words of the input text, in alphabetical order
<!DOCTYPE html>
<!-- e4_6.html - A solution to Exercise 4.6
-->
<html lang = "en">
<head>
<title> Exercise 4.6 </title>
<meta charset = "utf-8" />
</head>
<body>
<script type = "text/javascript">
<!--
var first = 1, second = 1, next, count;
str = prompt("Please input your sentence", "");
var words = str.split(" ");
words = words.sort();
words_len = words.length;
for (count = 0; count < words_len; count++)
document.write(words[count] + "<br/>");
// -->
</script>
</body>
</html>
BMSCE, ISE 64
Sample I/O:

BMSCE, ISE 65
Exercise 4.7:
Modify exercise4.6 to get a second input from the user, which is either
“ascending” or “descending”. Use this input to determine how to sort the
input words.
<!DOCTYPE html>
<html lang = "en">
<head>
<title> Exercise 4.7 </title> <meta charset = "utf-8" />
<script type = "text/javascript">
<!--
// A function to compare strings for reverse alphabetic order
function dec_order(a, b) {
if (a > b)
return -1;
else if (a < b)
return 1;
else return 0;
}
// -->
</script> </head> <body>
<script type = "text/javascript">
<!--
var order, str, words, word_len, count; BMSCE, ISE 66
Exercise 4.7 Continued…
// Get the input
str = prompt("Please input your sentence", "");
order = prompt("What order? (ascending or descending)", "");
// If the order is recognized, issue an error message
if (order != "descending" && order != "ascending")
document.write("Error - order is incorrectly specified <br/>");
// Otherwise, do the sort, depending on the requested order
else {
var words = str.split(" ");
if (order == "ascending")
words = words.sort();
else
words = words.sort(dec_order);
// Write out the results
words_len = words.length;
for (count = 0; count < words_len; count++)
document.write(words[count] + "<br/>");
}
// -->
</script>
</body>
</html> BMSCE, ISE 67
Sample I/O:

BMSCE, ISE 68
ascending descending

BMSCE, ISE 69
Exercise 4.9 : Function:e_names
Parameter: An array of names, represented as strings.
Returns: The number of names in the given array that end in either “ie” or “y”.
<!DOCTYPE html>
<!-- e4_9.html - A solution to Exercise 4.9
-->
<html lang = "en">
<head>
<title> Exercise 4.9 </title>
<meta charset = "utf-8" />
<script type = "text/javascript">
<!--
// Function e_names
// Parameter: an array of strings
// Returns: the number of given strings that end
// in either "ie" or "y"
function e_names(names) {
var len, index, count = 0;
len = names.length;
// Loop to use pattern matching to produce the count

BMSCE, ISE 70
Exercise 4.9 Continued . . .
for (index = 0; index < len; index++) {
position1 = names[index].search(/ie$/);
position2 = names[index].search(/y$/);
if (position1 + position2 > -2)
count++;
}
return count;
}
// -->
</script>
</head>
<body>
<script type = "text/javascript">
<!--
// Function e_names tester
var new_names = new Array ("mourya", "babu", "manju", "priya", "vinay");
result = e_names(new_names);
document.write("The number of special names that end in either \"ie\" or \"y\" is: " + result
+ "<br/>");// -->
</script></body></html>

BMSCE, ISE 71
Sample I/O:

BMSCE, ISE 72
Exercise 4.14:Function: reverser
Parameter: A number
Returns: The number with its digits in reverse order
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- e4_14.html - A solution to Exercise 4.14


-->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title> Exercise 4.14 </title>
<meta charset = "utf-8" />
<script type = "text/javascript">
<!--
var result;

// Function reverser
// Parameter: a number
// Returns: the number with its digits in reverse order
// Note: Math.floor must be used to get the integer part
// of the division operations
BMSCE, ISE 73
function reverser(num) {
var digit, position = 0;

// If the number has just one digit, that's it

if (num < 10)


return num;

// Get the first digit

result = num % 10;


num = Math.floor(num / 10);

// Loop to produce the result for the rest

do {
digit = num % 10;
result = 10 * result + digit;
num = Math.floor(num / 10);
} while (num >= 1);

return result;
}
// --> BMSCE, ISE 74
</script>
</head>

<body>
<script type = "text/javascript">
<!--
// Function reverser tester

var num1 = 2468, num2 = 7;


result = reverser(num1);
document.write("The reverse of 2468 is: " + result + "<br />");
result = reverser(num2);
document.write("The reverse of 7 is: " + result + "<br />");
// -->
</script>
</body>
</html>
Sample
I/O:
BMSCE, ISE 75
Web Technologies

Document Object Model


By
Mamatha

20 April 2025 BMSCE ISE 76


Window and Document

20 April 2025 BMSCE ISE 77


Window Object
Document Object
Form Object
Form Control Elements

20 April 2025 BMSCE ISE 78


20 April 2025 BMSCE ISE 79
HTML DOM (Document Object Model)
• When a web page is loaded, the browser creates a Document Object Model of the page.
Browser
<html>
<head> Prog.html
<title>Sample DOM Document</title>
</head>
<body>
<h1>An HTML Document</h1>
<p>This is a <i>simple</i> document.</p>
</body>
</html>
DOM Tree

Document Object

Paragraph Object

20 April 2025 BMSCE ISE 80


What is DOM (Document Object Model) ?

• The DOM is a W3C (World Wide Web Consortium) standard.


• The DOM defines a standard for accessing documents:
"The W3C Document Object Model (DOM) is a platform and language-neutral
interface that allows programs and scripts to dynamically access and update the
content, structure and style of a document.“
• Document Object Model
• Your web browser builds a model of the web page (the document) that
includes all the objects in the page (tags, text, etc)
• All of the properties, methods and events available to the web developer for
manipulating and creating web pages are organized into objects
• Those objects are accessible via scripting languages in modern web browsers

20 April 2025 BMSCE ISE 81


What can we do with DOM ?
With the Document object model, JavaScript gets all the power it needs to create dynamic
HTML:
• JavaScript can change all the HTML elements in the page
• JavaScript can change all the HTML attributes in the page
• JavaScript can change all the CSS styles in the page
• JavaScript can remove existing HTML elements and attributes
• JavaScript can add new HTML elements and attributes
• JavaScript can react to all existing HTML events in the page
• JavaScript can create new HTML events in the page

20 April 2025 BMSCE ISE 82


Document Object Model
<html>
<head> This is what the
<title>Sample DOM Document</title> browser reads
</head>
<body>
<h1>An HTML Document</h1>
<p>This is a <i>simple</i> document.
</body>
</html>

This is what the browser


displays on screen.

20 April 2025 BMSCE ISE 83


Document Object Model Tree
This is a drawing of the model that the
browser is working with for the page.

<html>
<head>
<title>Sample DOM Document</title>
</head>
<body>
<h1>An HTML Document</h1>
<p>This is a <i>simple</i>
document.
</body>
</html>

20 April 2025 BMSCE ISE 84


HTML DOM
• The HTML DOM is a standard for how to get, change add or delete HTML elements.
• The HTML DOM can be accessed with JavaScript (and with other programming
languages).

In the DOM, all HTML elements are defined as objects.


• The programming interface is the properties and methods of each object.
• A property is a value that you can get or set (like changing the content of an HTML
element).
• A method is an action you can do (like add or deleting an HTML element).

20 April 2025 BMSCE ISE 85


simple JS example

Mouse CLICK on the


Button “Try It”

20 April 2025 BMSCE ISE 86


simple JS example

<!DOCTYPE html>
<html> Sample I/O:
<body>
<h1>What Can JavaScript Do?</h1>
<p id="demo">JavaScript can change HTML content.</p>
<button type="button"
onclick="document.getElementById('demo').innerHTML =
'Hello JavaScript!'">
Click Me!</button>
</body>
</html>

20 April 2025 BMSCE ISE 87


simple JS example
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript">
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph
changed.";
}
</script>
</head>
<body>
<h1>My Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>
</body>
</html>

20 April 2025 BMSCE ISE 88


simple JS example
• This program has several simple controls.
Paragraph element
with id demo to display
the results

On button click change


the paragraph contents
<script type = "text/javascript">
function myFunction() {
This highlighted script makes
document.getElementById("demo").
reference to several objects in the innerHTML = "Paragraph changed.";
Document Object Model (DOM) }
</script>
20 April 2025 BMSCE ISE 89
document.getElementById("demo").innerHTML
is used to Get the HTML content of an element with id=“demo":

• Reference to several nodes in the model of the page that the browser
constructed
• document
• The root of the tree is an object of type HTMLDocument
• Using the global variable document, we can access all the nodes in the tree, as well as useful
functions and other global information
• title, body, images, links, forms, ...
• open, write, close, getElementById, ...

20 April 2025 BMSCE ISE 90


document.getElementById("demo").innerHTML

• getElementById(“demo”)
• This is a predefined function that makes use of the id that can be defined for
any element in the page
• An id must be unique in the page, so only one element is ever returned by
this function
• The argument to getElementById specifies which element is being
requested

20 April 2025 BMSCE ISE 91


Events

When a click happens, do submit my online purchase.


When a delete key press happens, do send this file to the recycle bin.
When a file download happens, do update the progress bar.
When a touch gesture happens, do apply this filter to this photo.

20 April 2025 BMSCE ISE 92


What is Event Handling?
• Capturing events and responding to them
• The system sends events to the program and the program responds
to them as they arrive
• Events can include things a user does - like clicking the mouse - or
things that the system itself does - like updating the clock. We will
exclusively focus on user-events.

20 April 2025 BMSCE ISE 93


Events and Their tag attributes:

20 April 2025 BMSCE ISE 94


Common HTML Events
Mouse Events
Event Description

onclick The event occurs when the user clicks on an element

ondblclick The event occurs when the user double-clicks on an element

onmousedown The event occurs when the user presses a mouse button over an element

onmouseover The event occurs when the pointer is moved onto an element

onmouseout The event occurs when a user moves the mouse pointer out of an element

onmouseup The event occurs when a user releases a mouse button over an element

20 April 2025 BMSCE ISE 95


Common HTML Events
Keyboard Events
Event Description

onkeydown The event occurs when the user is pressing a key


onkeypress The event occurs when the user presses a key

onkeyup The event occurs when the user releases a key

Form Events
Event Description

onfocus The event occurs when an element gets focus

oninput The event occurs when an element gets user input

onsubmit The event occurs when a form is submitted

20 April 2025 BMSCE ISE 96


Example for onkeydown and onkeyup:
<!DOCTYPE html>
<html> <head> <script>
function color(color) { Sample I/O:
document.getElementById("myForm").myInp
ut.style.background = color;
}
</script></head><body>
<form id="myForm"> Write a message:<br/>
<input type="text"
onkeydown="color('red')"
onkeyup="color('white')"
name="myInput">
</form></body> </html>
20 April 2025 BMSCE ISE 97
Example for onmouseover and onmouseout:
Sample I/O:

<!DOCTYPE html>
<html>
<body>
<h1 onmouseover="style.color='blue'" onmouseout="style.color='black'">
Mouse over this text
</h1>
</body>
</html>

20 April 2025 BMSCE ISE 98


Example Sample I/O:

<!DOCTYPE html>
<html>
<head>
<title>Click Anywhere!</title>
</head>
<body>
<script> document.addEventListener("click", changeColor, false);
function changeColor() {
document.body.style.backgroundColor = "#FFC926";
}
</script>
</body>
</html>

20 April 2025 BMSCE ISE 99


<!doctype html> Sample I/O:
<html>
<head>
<script>
function hov() {
var e = document.getElementById('hover');
e.style.display = 'none';
}
</script>
</head>
<body>
<div id="hover" onmouseover="hov()"
style="background-color:rgb(61, 240, 225);height:400px;width:400px;">
</div>
</body>
</html>

20 April 2025 BMSCE ISE 100


Event Driven Programs
• Programs that can capture and respond to events are called ‘event-
driven programs’

• JavaScript was specifically designed for writing such programs

• Almost all programs written in JavaScript are event-driven

20 April 2025 BMSCE ISE 101


JavaScript Handling of Events
• Events handlers are placed in the BODY part of a Web page as
attributes in HTML tags
• Events can be captured and responded to directly with JavaScript
one-liners embedded in HTML tags in the BODY portion
• Alternatively, events can be captured in the HTML code and then
directed to a JavaScript function for an appropriate response

20 April 2025 BMSCE ISE 102


Onclick Event: Example

Mouse CLICK on the


Button “SAMSUNG”

20 April 2025 BMSCE ISE 103


Onclick Event
<html><head>
<script type = "text/javascript" > Sample I/O:
function myFun()
{
alert("Samsung Button was Clicked");
}
</script>
<head><body>
<form>
<input type = "button" value="SAMSUNG" onclick="myFun();" />
</form>
</body></html>

20 April 2025 BMSCE ISE 104


Event-Driven Programming

onclick

REGISTERING ??

EventHandler

20 April 2025 BMSCE ISE 105


Registering Event Handlers
Method 1 Assigning event <input type = "button" value=“SAMSUNG"
handler code onclick="alert(‘SAMSUNG Button was Clicked');" />
to event

Method 2 Assigning event <script type = "text/javascript" >


handler function function myFun()
name { alert("Samsung Button was Clicked");}
to event </script>

<input type = "button" value="SAMSUNG" onclick="myFun();"


/>
20 April 2025 BMSCE ISE 106
Registering Event Handlers
Method 1 Assigning event <input type = "button" value=“SAMSUNG"
handler code onclick="alert(‘SAMSUNG Button was Clicked');" />
to event

Method 2 Assigning event <script type = "text/javascript" >


handler function function myFun()
name { alert("Samsung Button was Clicked");}
to event </script>

<input type = "button" value="SAMSUNG" onclick="myFun();"


/>
---------------
<input type = "button" value=“SAMSUNG" id="b1" />

document.getElementById(“b1").onclick = myFun;

20 April 2025 BMSCE ISE 107


Element Access in JavaScript

20 April 2025 BMSCE ISE 108


Method 1: Element Access in JavaScript
<html>
<body>
<form name=“myForm” >
<input type = "button" name="turnItOn" />
</form>
</body>
</html>

DOM Address of button


Method 1: using forms and element arrays

var dom = document.forms[0].elements[0];

20 April 2025 BMSCE ISE 109


Example
<body>
<html> <form >
<head> <input type = "button" value="NOKIA" name="b1"
/>
<script type = "text/javascript" > <input type = "button" value="SAMSUNG"
function myFun1() name="b2" />
</form>
{ alert("Nokia Button was
<script type = "text/javascript" >
Clicked"); } var b1_addr= document.forms[0].elements[0];
function myFun2() b1_addr.onclick=myFun1;
{alert("Samsung Button was var b2_addr= document.forms[0].elements[1];
b2_addr.onclick=myFun2;
Clicked"); }
</script>
</script> </body>
<head> </html>

20 April 2025 BMSCE ISE 110


Sample I/O:

20 April 2025 BMSCE ISE 111


Example

20 April 2025 BMSCE ISE 112


Method 1: Element Access in JavaScript using forms and element arrays
<html><head>
<script type = "text/javascript">
function myFunction() {
var dom = document.forms[0].elements[0];
dom.value="Text Box Changed";
Sample I/O:
} </script>
</head> <body>
<h1>My Web Page</h1>
<form name="myForm">
<input type="text" name="par"/>
</br>
<input type = "button" onclick="myFunction();" name="turnItOn" value="CLICK" />
</form>
</body> </html>
20 April 2025 BMSCE ISE 113
Question: Find what happens when user click on the Button?

<html><head>
<script type = "text/javascript">
function myFunction() {
var dom = document.forms[0].elements[1];
dom.value="Text Box Changed";
Sample I/O:
} </script>
</head> <body>
<h1>My Web Page</h1>
<form name="myForm">
<input type="text" name="par"/>
</br>
<input type = "button" onclick="myFunction();" name="turnItOn" value="CLICK" />
</form>
</body> </html>

20 April 2025 BMSCE ISE 114


Question: Find what happens when user clicks on Second Button?
<html><head>
<script type = "text/javascript">
function myFunction() {
var dom = document.forms[1].elements[0];
dom.value="Text Box Changed";
} </script>
</head><body>
<h1>My Web Page</h1> Sample I/O:
<form name="myForm1">
<input type="text" name="par"/> </br> <input type = "button";" name="turnItOn1" value=“FIRST" />
</form>
<form name="myForm2">
<input type="text" name="par"/></br>
<input type = "button" onclick="myFunction();" name="turnItOn2" value=“SECOND" />
</form></body> </html>

20 April 2025 BMSCE ISE 115


Method 2: Element Access in JavaScript
<html>
<body>
<form name=“myForm”>
<input type = "button" name="turnItOn" />
</form>
</body>
</html>

DOM Address of button


Method 2: Using the name attributes
var dom = document.myForm.turnItOn;

20 April 2025 BMSCE ISE 116


Example:
<html> <form name="mobileForm">
<head> <input type = "button" value="NOKIA" name="b1" />
<script type = "text/javascript" > <input type = "button" value="SAMSUNG" name="b2" />
</form>
function myFun1()
{ <script type = "text/javascript" >
alert("Nokia Button was Clicked"); var b1_addr= document.mobileForm.b1;
} b1_addr.onclick=myFun1;
var b2_addr= document.mobileForm.b2;
function myFun2()
b2_addr.onclick=myFun2;
{ </script>
alert("Samsung Button was
Clicked"); </body>
} </html>
</script>
<head>
<body>

20 April 2025 BMSCE ISE 117


Method 3: Element Access in JavaScript
<html>
<body>
<form name=“myForm”>
<input type = "button" id="turnItOn" />
</form>
</body>
</html>

DOM Address of button


Method 3: element Id
var dom = document.getElementById(“turnItOn”);

20 April 2025 BMSCE ISE 118


Example:
<html> <form name="mobileForm">
<head> <input type = "button" value="NOKIA" id="b1" />
<input type = "button" value="SAMSUNG" id="b2" />
<script type = "text/javascript" > </form>
function myFun1()
{ <script type = "text/javascript" >
var b1_addr= document.getElementById("b1");
alert("Nokia Button was Clicked");
b1_addr.onclick=myFun1;
} var b2_addr= document.getElementById("b2");
function myFun2() b2_addr.onclick=myFun2;
{ </script>

alert("Samsung Button was Clicked"); </body>


} </html>
</script>
<head>
<body>

20 April 2025 BMSCE ISE 119


Element access for checkboxes:
<html> </head>
<head> <body>
<title>Sample DOM Document</title> <form id = "vehicleGroup">
<script type="text/javascript"> <label><input type = "checkbox" name = "vehichles"
function myfun(){ value = "bus" /> Bus</label>
<label><input type = "checkbox" name = "vehichles"
var numChecked = 0;
value = "car" /> Car</label>
var dom = document.getElementById("vehicleGroup"); <label><input type = "checkbox" name = "vehichles"
for (index = 0;index < 3;index++) value = "bike" /> Bike</label>
if(dom.vehichles[index].checked) </form>
numChecked++; <button onclick="myfun()">Submit</button>
alert("Number of Checkboxes Checked "+numChecked); </body>
</html>
} Sample I/O:
</script>

20 April 2025 BMSCE ISE 120


Accessing Checkboxes
<form id = "vehicleGroup>
<input type = "checkbox" name = "vehichles" value = "bus" /> Bus
<input type = "checkbox" name = "vehichles" value = "car" /> Car
<input type = "checkbox" name = "vehichles" value = "bike" /> Bike
</form>

var numchecked = 0;
var dom = document.get ElementById("vehicleGroup");
for (index = 0;index <dom.vehicles.length;index++)
if(dom.vehicles[index].checked)
numChecked++;

20 April 2025 BMSCE ISE 121


HTML events are "things" that happen to HTML elements.

When JavaScript is used in HTML pages, JavaScript


can "react" on these events.

20 April 2025 BMSCE ISE 122


Question1
• Try to fix the following code. When user clicks on the paragraph content “Click
me” the text content should change to “GOOD JOB!”

<!DOCTYPE html>
<html>
<body>
<p someevent="this.innerHTML='GOOD JOB!'">Click me.</p>
</body>
</html>

20 April 2025 BMSCE ISE 123


Answer
• Try to fix the following code. When user clicks on the paragraph content “Click
me” the text content should change to “GOOD JOB!”

<!DOCTYPE html>
<html>
<body>
<p onclick="this.innerHTML='GOOD JOB!'">Click me.</p>
</body>
</html>

20 April 2025 BMSCE ISE 124


Question2
• Try to fix the following code. When user clicks on the button, trigger myFunction() with an event
<!DOCTYPE html>
<html><body>
<input type = "button" value=“Click Me" />
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
</script>
</body></html>

20 April 2025 BMSCE ISE 125


Answer
• Try to fix the following code. When user clicks on the button, trigger myFunction() with an event
<!DOCTYPE html>
<html>
<body>
<input onclick=“myFunction();” type = "button" value=“Click Me" />
<p id="demo"></p>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Hello World";
}
</script>
</body></html>

20 April 2025 BMSCE ISE 126


Question3

• The <span> element should do something when someone moves the mouse over
it. Try to fix it!
<!DOCTYPE html>
<html>
<body>
<span someevent="this.style.color='red'">Mouse over me!</span>
</body>
</html>

20 April 2025 BMSCE ISE 127


Answer

• The <span> element should do something when someone moves the mouse over
it. Try to fix it!
<!DOCTYPE html>
<html>
<body>
<span onmouseover="this.style.color='red'">
Mouse over me!
</span>
</body>
</html>

20 April 2025 BMSCE ISE 128


Example Program: Signup Form
Demonstration: Validating Form Input

20 April 2025 BMSCE ISE 129


Signup Form
<html> <head>
<body>
<script type = "text/javascript" > <form name = "myForm" action=""
function chkpasswords() { onsubmit="return(chkpasswords());">
if (document.getElementById("firstpwd").value == ""){ <p>
</label> User Name: <input type = "text" id="username">
alert('You have not entered a password, please enter ');
</label>
document.getElementById("firstpwd").focus(); <br />
return false; } <br />
if (document.getElementById("firstpwd").value !=
</label> Password: <input type = "password" id = "firstpwd" />
</label>
document.getElementById("secondpwd").value) { <br />
alert('The two password you entered are not same, please re- <br />
enter'); <label> Retype Password: <input type = "password" id =
document.getElementById("firstpwd").focus(); "secondpwd" /> </label>
document.getElementById("firstpwd").select(); <br />
<br />
return false; }
<input type = "submit" name = "submit" />
else { alert('The two password you entered are same'); </p>
return true; }}
</form>
</script> </head> </body>
20 April 2025
</html>
BMSCE ISE 130
<html> <head>
Example program
<script type = "text/javascript" >
function chkpasswords() { <body>
if (document.getElementById("firstpwd").value == ""){ <form name = "myForm" action=""
alert('You have not entered a password, please enter '); onsubmit="return(chkpasswords());">
document.getElementById("firstpwd").focus(); <p>
return false;
</label> User Name:
}
<input type = "text" id="username"> </label>
if (document.getElementById("firstpwd").value !=
<br /> <br />
document.getElementById("secondpwd").value)
</label> Password:
{
<input type = "password" id = "firstpwd" /> </label>
alert('The two password you entered are not same, please re-enter');
<br /> <br />
document.getElementById("firstpwd").focus();
<label> Retype Password:
document.getElementById("firstpwd").select();
<input type = "password" id = "secondpwd" /> </label>
return false;
}
<br /><br />
else {
<input type = "submit" name = "submit" />
alert('The two password you entered are same');
</p> </form>
return true; </body></html>
}
}
</script> </head>
20 April 2025 BMSCE ISE 131
Question: What changes should be made to the following program so the control will be transferred to “bms.html”
when two passwords given by the user are same.

<html> <head>
<script type = "text/javascript" >
</script> </head>
<body>
<form name = "myForm" action="" onsubmit="return(chkpasswords());">
<p>
</label> User Name:
<input type = "text" id="username"> </label>
<br /> <br />
</label> Password:
<input type = "password" id = "firstpwd" /> </label>
<br /> <br />
<label> Retype Password:
<input type = "password" id = "secondpwd" /> </label>
<br /><br />
<input type = "submit" name = "submit" />
</p> </form>
</body></html>

20 April 2025 BMSCE ISE 132


Handling Events

• From Body Element


• Example events: onload, onunload
• From Button Elements
• Example events: onclick
• From Textbox and Password Elements
• Example events: blur, focus, change, select

20 April 2025 BMSCE ISE 133


Demonstration: Example Program

Body Element: Load and Unload events

20 April 2025 BMSCE ISE 134


Program
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function myFun1() { bms.html:
alert("Welcome !");
} <!DOCTYPE html>
<html>
function myFun2() {
<head>
alert("Thank you for visiting !"); </head>
} <body">
</script> <h1>BMSCE homepage</h1>
</head> </body>
<body onload="myFun1()" onunload="myFun2()">
</html>
<h1>BMS College of Engineering</h1>
<a href="bms.html">BMS</a>
</body>
</html>
20 April 2025 BMSCE ISE 135
Dynamic Documents with Javascript
By
Mamatha

Web Application Development

20 April 2025 BMSCE,ISE 136


Dynamic HTML
• A dynamic HTML document is an HTML document that, in some way, can be changed while it is
being displayed by a browser.
• A dynamic HTML document is an HTML document whose tag attributes, tag contents or element
style properties can be changed by user interaction or the occurrence of a browser event after
the document has been and is still being, displayed.
• Dynamic changes can be made with an embedded script that accesses the elements of the
document.

20 April 2025 BMSCE,ISE 137


Positioning elements
• Absolute positioning
• Relative positioning
• Static positioning

20 April 2025 BMSCE,ISE 138


Eg1 for Absolute positioning: absPos.html
<body>
<html>
<p class = "regtext">
<head> Apple is the common name for any tree of the genus
<title> Absolute positioning </title> Malus, of the family Rosaceae. Apple trees grow in any of
<style type = "text/css"> the temperate areas of the world. Some apple blossoms
/* A style for a paragraph of text */ are white, but most have stripes or tints of rose. Some
.regtext {font-family: Times; font-size: 14pt; apple blossoms are bright red. Apples have a firm and
width: 600px} fleshy structure that grows from the blossom. The colors
/* A style for the text to be absolutely positioned */ of apples range from green to very dark red. The wood of
apple trees is fine-grained and hard. It is, therefore, good
.abstext {position: absolute; top: 25px; left: 50px;
for furniture construction. Apple trees have been grown
font-family: Times; font-size: 24pt; for many centuries. They are propagated by grafting
font-style: italic; letter-spacing: 1em; because they do not reproduce themselves.
color: rgb(102,102,102); width: 500px} </p>
</style> <p class = "abstext">
</head> APPLES ARE GOOD FOR YOU
</p> </body> </html>

20 April 2025 BMSCE,ISE 139


Sample I/O:

20 April 2025 BMSCE,ISE 140


Eg2 for Absolute positioning: absPos2.html:
<html xmlns = "http://www.w3.org/1999/xhtml"> <body>
<head> <div class = "regtext">
Apple is the common name for any tree of the genus Malus, of
<title> Nested absolute positioning </title> the family Rosaceae. Apple trees grow in any of the temperate
<style type = "text/css"> areas of the world. Some apple blossoms are white, but most
/* A style for a paragraph of text */ have stripes or tints of rose. Some apple blossoms are bright
.regtext {font-family: Times; font-size: 14pt; width: red. Apples have a firm and fleshy structure that grows from
500px; position: absolute; top: 100px; left: 100px;} the blossom. The colors of apples range from green to very
/* A style for the text to be absolutely positioned */ dark red. The wood of apple trees is fine-grained and hard.
It is, therefore, good for furniture construction. Apple trees
.abstext {position: absolute; top: 25px; left: 50px; have been grown for many centuries. They are propagated by
font-family: Times; font-size: 24pt; grafting because they do not reproduce themselves.
font-style: italic; letter-spacing: 1em; <span class = "abstext">
color: rgb(102,102,102); width: 400px;} APPLES ARE GOOD FOR YOU
</span>
</style> </div>
</head> </body>
</html>

20 April 2025 BMSCE,ISE 141


Sample I/O:

20 April 2025 BMSCE,ISE 142


Eg for Relative positioning:
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title> Relative positioning </title>
</head>
<body style = "font-family: Times; font-size: 24pt;">
<p>
Apples are <span style = "position: relative; top: 10px;
font-family: Times; font-size: 48pt; font-style: italic; color: red;"> Sample I/O:
GOOD </span> for you.
</p>
</body>
</html>

20 April 2025 BMSCE,ISE 143


Moving elements:
<p>
<html>
<label> x - coordinate: <input type = "text" id =
<head> "leftCoord" size = "3" /> </label> <br/>
<title>Moving Elements</title> <label> y - coordinate: <input type = "text" id =
<script type = "text/javascript"> "topCoord" size = "3" /> </label> <br/>
<input type="button"
function moveIt(elem, newTop, newLeft)
value="Move It"
{ dom = onclick = "moveIt('utsav’,
document.getElementById(elem).style;
document.getElementById('topCoord').value,
dom.top = newTop + "px"; document.getElementById ('leftCoord').value)"
dom.left = newLeft + "px"; />
} </p> </form>
</script> <div id = "utsav" style =
"position:absolute;top:115px;left:0;">
</head>
<img src = "utsav.jpg" height="300" width="300" alt =
<body> "UTSAV 2023" />
<form> </div> </body> </html>

20 April 2025 BMSCE,ISE 144


Sample I/O:
Sample I/O:

20 April 2025 BMSCE,ISE 145


Element Visibility
• Document elements can be specified to be visible or hidden with the
value of their visibility property.
• Two possible values for visibility are visible and hidden.
• Appearance or disappearance of an element can be controlled by the
user through a widget.

20 April 2025 BMSCE,ISE 146


Example Program
<html> <head>
<body>
<title>Element Visibility</title> <form>
<script type = "text/javascript"> <div id = "utsav" style = "position:relative;
function flipImag() visibility:visible">
{ dom = <img src = "utsav.jpg" height="300"
document.getElementById("utsav").style; width="300" alt = "UTSAV 2023" />
</div>
if(dom.visibility == "visible")
<p><br><input type="button" value="Toggle
dom.visibility = "hidden"; UTSAV" onclick = "flipImag()" /></p>
else </form>
dom.visibility = "visible"; </body>
</html>
}
</script> </head>
20 April 2025 BMSCE,ISE 147
Sample I/O:
Sample I/O:

20 April 2025 BMSCE,ISE 148


Changing colors and fonts
• Foreground and background colors of document display can be
changed
• Font properties can also be changed.

20 April 2025 BMSCE,ISE 149


Eg: dynColors.html:
<html xmlns = "http://www.w3.org/1999/xhtml"> <body>
<p style = "font-family: Times; font-style: italic;
<head>
font-size: 24pt" >
<title> Dynamic colors </title> This small page illustrates dynamic setting of the
<script type = "text/javascript"> foreground and background colors for a document
<!-- </p>
// The event handler function to dynamically set the <form action = "">
// color of background or foreground <p>
Background color: <input type = "text" name = "background"
function setColor(where, newColor) {
size = "10" onchange = "setColor('background',this.value)" />
if (where == "background") <br />
document.body.style.backgroundColor = newColor; Foreground color: <input type = "text" name = "foreground"
else size = "10" onchange = "setColor('foreground',this.value)" />
document.body.style.color = newColor; <br />
} </p>
// --> </form>
</body>
</script>
</html>
</head>

20 April 2025 BMSCE,ISE 150


Sample I/Os:

20 April 2025 BMSCE,ISE 151


Stacking of Elements
• The zIndex property sets or returns the stack order of a positioned
element.
• An element with greater stack order (1) is always in front of another
element with lower stack order (0).
• This property is useful if you want to create overlapping elements.
• The top and left properties allow the placement of an element anywhere in the two dimensions of the display of a
document.
• Although the display is restricted to two physical dimensions, the effect of a third dimension is possible through the simple
concept of stacked elements, such as that used to stack windows in graphical user interfaces.
• Although multiple elements can occupy the same space in the document, one is considered to be on top and is displayed.
• The top element hides the parts of the lower elements on which it is superimposed.
• The placement of elements in this third dimension is controlled by the z-index attribute of the element.
• An element whose z-index is greater than that of an element in the same space will be displayed over the other element,
effectively hiding the element with the smaller z-index value.
• The JavaScript style property associated with the z-index attribute is zIndex.
20 April 2025 BMSCE,ISE 152
Eg for Stacking:
function move(curStack) {
<html > var oldStack=document.getElementById(stack1).style;
<head><title>Stacking Paragraphs</title> oldStack.zIndex="0";
<style type="text/css"> var newStack=document.getElementById(curStack).style;
.para1 { border: solid thick #C0C0C0; padding: 1in; newStack.zIndex="10";
width:180px; stack1=document.getElementById(curStack).id;
background-color:#0000D0; color:white; }
position:absolute; top:70px; left:4in; z-index:1; } </script>
</head>
.para2 { border: solid thick #808000; padding: 1in;
width:180px; <body>
<h2><center>Stacking of Paragraphs on top of each
background-color:red; color:white;
other</center></h2>
position:absolute; top:110px; left:5in; z-index:2; } <p class="para1" id="stack1" onmouseover="move('stack1')">
.para3 { border: solid thick #00ffff; padding: 1in; width:180px; SJM Institute of Technology </p>
background-color:green; color:white; <p class="para2" id="stack2" onmouseover="move('stack2')">
position:absolute; top:150px; left:6in; z-index:3; } BMS College of Engineering </p>
<p class="para3" id="stack3" onmouseover="move('stack3')">
</style>
MS Ramaiah Institute of Technology </p>
<script type="text/javascript"> </body>
var stack1="stack1"; </html>

20 April 2025 BMSCE,ISE 153


Sample I/O:

20 April 2025 BMSCE,ISE 154


Slow Movement of Elements
• The only way to move an element slowly is to move it by small amounts many
times, with the moves separated by small amounts of time.
• JavaScript has a Window methods that is capable of this task: setTimeout.
• The setTimeout method takes two parameters: a string of JavaScript code to be
executed and a number of milliseconds of delay before executing the given code.

20 April 2025 CSE, BMSCE 155


Example program
<html> <head> <title>Moving Text</title>
<script type="text/javascript">
if((x!=finalx)||(y!=finaly))
var dom, x, y, finalx=500, finaly=500;
{
function initText() { /* Convert the string values of left and top to
dom = document.getElementById('theText').style; numbers by stripping off the units */
var x=dom.left; var y=dom.top; dom.left=x + "px";
x=x.match(/\d+/); y=y.match(/\d+/); dom.top=y + "px";
moveText(x,y); setTimeout("moveText(" + x + "," + y + ")", 1);
} }
function moveText(x,y) { }
if(x!=finalx) </script>
if(x>finalx) <body onload = "initText()">
x--; <p>
else if(x<finalx) <span id = 'theText' style = "position:absolute; left:100px;
x++; top:100px; font:bold 20pt cambria; color:blue;">
if(y!=finaly) Jump into BMS College of Engineering
if(y>finaly) </span>
y--; </p>
else if(y<finaly) </body>
y++; </html>
20 April 2025 BMSCE,ISE 156
Locating Cursor
• A mouse-click event is an implementation of the Mouse-Event interface, which defines two pairs of
properties that provide geometric coordinates of the position of the element in the display that created the
event.
• One of these pairs, clientX and clientY, gives the coordinates of the element relative to the upper-left corner
of the browser display window, in pixels.
• The other pair, screenX and screenY, also gives coordinates of the element, but relative to the client
computer’s screen.
• In the next example, where.html, two pairs of text boxes are used to display these four properties every time
the mouse button is clicked.
• The handler is triggered by the onclick attribute of the body element.
• The call to the handler in this example sends event, which is a reference to the event object just created in
the element, as a parameter.

20 April 2025 CSE, BMSCE 157


Illustration Screen and Client Coordinates

Screen Y

Client Y
Screen X
Client X

20 April 2025 CSE, BMSCE 158


Example Program
<html>
<head> <title>Locating Mouse Cursor</title>
<script type="text/javascript"> <form>
function findIt(evt) <p> Within the BROWSER X and Y Co-ordinates (Browser Top
Left Corner):<br />
{ document.getElementById("xcoor1").value =
evt.clientX; clientX: <input type="text" id="xcoor1" size="4"/>
clientY: <input type="text" id="ycoor1" size="4"/>
document.getElementById("ycoor1").value =
evt.clientY; <br><br><br>
Within the COMPUTER SCREEN X and Y Co-ordinates
document.getElementById("xcoor2").value =
evt.screenX;
(Computer Screen Top Left Corner): <br />
screenX: <input type="text" id="xcoor2" size="4"/>
document.getElementById("ycoor2").value = screenY: <input type="text" id="ycoor2" size="4"/>
evt.screenY; }
</p>
</script> </form>
</head> </body> </html>
<body onclick="findIt(event)">

20 April 2025 CSE, BMSCE 159


Sample I/O:

20 April 2025 BMSCE,ISE 160


// *****************************************
Dynamic values: // The event handler function to change the value of the
// textarea
<html xmlns = function messages(adviceNumber) {
"http://www.w3.org/1999/xhtml">
document.getElementById("adviceBox").value =
<head> helpers[adviceNumber];
<title> Dynamic values </title> }
<script type = "text/javascript"> // ********************************************
</script>
var helpers = ["Your name must be in the
form: \n \ </head>
<body>
first name, middle initial., last name", <form action = "">
"Your email address must have the form: \ <p style = "font-weight: bold">
user@domain", <span style = "font-style: italic">
"Your user ID must have at least six Customer information
characters", </span>
<br /><br />
"Your password must have at least six \
Name: <input type = "text" onmouseover = "messages(0)"
characters and it must include one digit", onmouseout = "messages(4)" />
"This box provides advice on filling out\ <br />
the form on this page. Put the mouse cursor
over any \
input field to get advice"]
20 April 2025 BMSCE,ISE 161
Email: <input type = "text" onmouseover =
"messages(1)"
onmouseout = "messages(4)" />
<textarea id = "adviceBox" rows = "3" cols = "50"
<br /> <br /> style = "position: absolute; left:
<span style = "font-style: italic"> 250px;
To create an account, provide the following: top = 0px">
</textarea>
</span>
<br /><br />
<br /> <br /> <input type = "submit" value = "Submit"
User ID: <input type = "text" onmouseover = />
"messages(2)” onmouseout = "messages(4)" /> <input type = "reset" value = "Reset" />
<br /> </p>
Password: <input type = "password" </form>
</body>
onmouseover = "messages(3)" </html>
onmouseout = "messages(4)" />
<br />

20 April 2025 BMSCE,ISE 162


Sample I/O:

20 April 2025 BMSCE,ISE 163

You might also like