Module 2
Module 2
Presentation Material
Department of Computer Science & Engineering
Semester
Course Code: 20OE0003 7
:
Course Title: WEB TECHNOLOGIES Year: IV
Course Name & Course Code Department of Computer Science & Engineering 1
MODULE 3
Overview of JavaScript; Object orientation and JavaScript; General syntactic, characteristics; Primitives, operations, and expressions;
Screen output and keyboard input. Control statements; Arrays; Functions, Constructors; A brief introduction on pattern matching using regular
expressions, DOM Events
Online
Resources:
https://www.javatpoint.com/javascript-tutorial
Course Name & Course Code Department of Computer Science & Engineering 2
JavaScript
• JavaScript, which was originally developed at Netscape by Brendan Eich, was initially named Mocha but
soon after was renamed LiveScript.
• In late 1995 LiveScript became a joint venture of Netscape and Sun Microsystems, and its name again was
changed, this time to JavaScript.
JavaScript Objects
• In JavaScript, objects are collections of properties, which correspond to the members of
classes in Java and C++.
• Each property is either a data property or a function or method property.
• Data properties appear in two categories: primitive values and references to other
objects.
• JavaScript uses nonobject types for some of its simplest types; these nonobject types are
called primitives.
• All objects in a JavaScript program are indirectly accessed through variables.
General Syntactic Characteristics
• Scripts can appear directly as the content of a <script> tag.
• The type attribute of <script> must be set to “text/javascript”.
• The JavaScript script can be indirectly embedded in an HTML document with the src
attribute of a <script> tag, whose value is the name of a file that contains the script
Declaring Variables
• A variable can be used for anything.
• Variables are not typed; values are.
• A variable can have the value of any primitive type, or it can be a reference to any object.
• The type of the value of a particular appearance of a variable in a program can be
• determined by the interpreter.
• A variable can be declared either by assigning it a value, in which case the
interpreter implicitly declares it to be a variable, or by listing it in a declaration
statement that begins with the reserved word var
Example
var counter;
pi = 3.14159265;
quarterback = "Elway";
stop_flag = true;
Numeric Operators
The binary operators
• + for addition, - for subtraction, * for multiplication, / for division, and %
• for modulus.
• The unary operators are plus (+), negate (-), decrement (--), and increment (++).
The increment and decrement operators can be either prefix or postfix.
a=7
(++a) * 3=?
(a++) * 3=?
• All numeric operations are done in double-precision floating
point.
c = 3 + a * b; c=11
d = b / a / 2;
d=1
var a=56;
b=87;
c=3*(a+b);
document.writeln(c);
</script>
<p id="demo"></p>
</body>
</html>
16
In JavaScript, objects are king. If you
understand objects, you understand
JavaScript.
17
*Built In Object: Math,Number,String,Date
Built in objects -Math Object
The Math Object(
https://www.w3schools.com/js/js_math.asp)
• The Math object provides a collection of properties of Number
objects and methods that operate on Number objects
• The Math object has methods for the trigonometric functions,
such as sin and cos
• floor, to truncate a number;
• round, to round a number;
• and max, to return the largest of two given numbers.
https://www.w3schools.com/js/js_math.asp
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.round()</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = Math.round(4.4);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Math.sin()</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML =
"The sine value of 90 degrees is " + Math.sin(90 * Math.PI / 180);
</script>
</body>
</html>
Built in Object-The Number Object
• The Number object includes a collection of useful properties that
have constant values.
• The properties are referenced through Number.
Example:Number.MIN_VALUE,Number.MAX_VALUE
METHODS OF NUMBER OBJECT
Methods Description
toExponential() It returns the string that represents exponential notation of the given number.
toFixed() It returns the string that represents a number with exact digits after a decimal point.
</script>
</body>
</html>
• The Number object has a method, toString, which it inherits from Object
but overrides.
• The toString method converts the number through which it is called to a
string.
var price = 427,
str_price;
...
str_price = price.toString();
//We can convert quantity into a number using the Number function like this:
Number(quantity);
• The second way , parseInt and parseFloat, are not String methods, so they are not called through
String objects. They operate on the strings given as parameters
• The parseInt function searches its string parameter for an integer literal.
• If one is found at the beginning of the string, it is converted to a number and returned.
• If the string does not begin with a valid integer literal, NaN is returned.
• The parseFloat function searches for a floating-point literal, which could have a decimal point, an
exponent, or both.
<!DOCTYPE html>
<html>
<body>
<script>
var a1=Number.parseInt("10") ; //or parseInt(“10”)
var b1=parseInt(“10.33”);
document.writeln ( n1);
</script>
</body>
</html>
29
<!DOCTYPE html>
<html> document.writeln("the value of z is"+
<body> "<br>"+ z +"<br>");
<script> document.writeln("the value of l is"+
var x=102;//integer value "<br>"+ l+"<br>");
var y=102.7;//floating point value x=Number.parseInt("40 50 12");
var z=13e4;//exponent value, output: document.writeln("the value of x is"+
130000 "<br>"+ x+ "<br>");
var n=new Number(16); t=parseInt("hello 12");
document.write(x+" "+y+" "+z+" "+n); document.writeln("the value of l is"+
"<br>"+ t+"<br>");
document.write("<br>");
d=parseInt(" 12 hello ");
document.write(x+y+z+n);
document.writeln("the value of d is"+
document.write("<br>"); "<br>"+ d+ "<br>");
document.writeln(Number.parseInt("10")) document.writeln(x.toExponential());conve
; rts number to string in exponent form
document.writeln("<br>"); document.writeln(x.toString());//converts
x=Number.parseInt("20"); number to string
y=Number.parseInt("40"); </script>
z=x+y; </body> 30
<!DOCTYPE html> // EXAMPLE REPEATED WITH EVENTS AND FUNCTION
<html>
<body>
<p>Click the button to parse different strings.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<p id="demo1"></p>
<script>
function myFunction() {
var a=Number.parseInt(“10”);
// var a = parseInt("10") + "<br>";
var b = parseInt("10.00") + "<br>";
var c = parseInt("10.33") + "<br>";
var d = parseInt("34 45 66") + "<br>";//parse Int takes only the first argument and converts it into integer.
var e = parseInt(" 60 ") + "<br>";
var f = parseInt("40 years") + "<br>";
var g = parseInt("He was 40") + "<br>";
var h = parseInt("10", 10)+ "<br>";
var i = parseInt("010")+ "<br>";
var j = parseInt("10", 8)+ "<br>";
var k = parseInt("0x10")+ "<br>";
var l = parseInt("10", 16)+ "<br>";
var n = a + b + c + d + e + f + g + "<br>" + h + i + j + k +l; //no addition here ,only we are displaying the converted value
document.getElementById("demo").innerHTML = n;
var a1=Number.parseInt("10") ; //or parseInt(“10”)
var b1=parseInt(“10.33”);
}
</script>
</body>
</html>
Built in Object-String Properties and Methods
• String methods can always be used through String primitive
values, as if the values were objects.
• The String object includes one property, length, and a large
collection of methods.
• The number of characters in a string is stored in the length
property
var str = "George";
var len = str.length;
len is set to the number of characters in str, namely, 6.
*String Methods
33
• Example
Assignment Statements
• There is a simple assignment operator, denoted by =, and a host of
compound assignment operators, such as += and /=.
• a += 7;
means the same as
• a = a + 7;
<html> <script>
<body> document.getElementById("demo").innerHTML =
"'John' is " + typeof "John" + "<br>" +
<h1>JavaScript Operators</h1> "3.14 is " + typeof 3.14 + "<br>" +
<h2>The typeof Operator</h2> "NaN is " + typeof NaN + "<br>" +
"false is " + typeof false + "<br>" +
<p>The typeof operator returns the type of a variable, object, "[1, 2, 3, 4] is " + typeof [1, 2, 3, 4] + "<br>" +
function or expression:</p> "{name:'John', age:34} is " + typeof {name:'John', age:34} +
"<br>" +
<p id="demo"></p> "new Date() is " + typeof new Date() + "<br>" +
"function () {} is " + typeof function () {} + "<br>" +
"myCar is " + typeof myCar + "<br>" +
"null is " + typeof null;
</script>
</body>
</html>
36
*Screen Output and Keyboard Input
• JavaScript models the HTML document with the Document object.
• The window in which the browser displays an HTML document is
modeled with the Window object.
• The Window object includes two properties, document and window.
• The document property refers to the Document object.
• The window property is self-referential; it refers to the Window
object.
• The Document object has several properties and methods.
Commonly used is write, which is used to create output, which is
dynamically created HTML document content.
document.write("The result is: ", result, "<br />");
• The parameter of write can include any HTML tags and
content.
• The write method actually can take any number
• of parameters. Multiple parameters are catenated and placed
in the output.
• Window includes three methods that create dialog boxes for
three specific kinds of user interactions.
• The three methods— alert, confirm, and prompt
• The alert method opens a dialog window and displays its
parameter in
that window. It also displays an OK button.
// Convert the user input to a number using the unary plus operator (+)
var number = +userInput;
Control Expressions
• The expressions upon which statement flow control can be based include
primitive values, relational expressions, and compound expressions.
• The result of evaluating a control expression is one of the Boolean values
true or false
• A relational expression has two operands and one relational
operator.
• If the two operands in a relational expression are not of the
same type and the operator is neither === nor !==, JavaScript
will attempt to convert the operands to a single type.
• If a and b reference different objects, a == b is never true, even if
the objects have identical properties. a == b is true only if a and
b reference the same object.
Selection Statements
• The selection statements (if-then and if-then-else). Either single statements or compound statements can
be selected
if (a > b)
document.write("a is greater than b <br />");
else {
a = b;
document.write("a was not greater than b <br />",
"Now they are equal <br />");
}
switch (expression) {
case value_1: Note :Save the next program as borders2.js
50
The Date Object tutorial reference:
https://www.javatpoint.com/javascript-date
• A Date object is created with the new operator and the Date
constructor, which has several forms.
• var today = new Date();
• The date and time properties of a Date object are in two forms:
local and Coordinated Universal Time (UTC)
// Get the current date
"Minute: " + minute + "<br />",
var today = new Date();
"Second: " + second + "<br />",
// Fetch the various parts of the date
"Millisecond: " + millisecond + "<br />");
var dateString = today.toLocaleString();
// Time a loop
var day = today.getDay();
var dum1 = 1.00149265, product = 1;
var month = today.getMonth();
var start = new Date();
var year = today.getFullYear();
for (var count = 0; count < 10000; count++)
var timeMilliseconds = today.getTime();
product = product + 1.000002 * dum1 /
var hour = today.getHours();
1.00001;
var minute = today.getMinutes();
var end = new Date();
var second = today.getSeconds();
var diff = end.getTime() - start.getTime();
var millisecond = today.getMilliseconds();
document.write("<br />The loop took " + diff +
// Display the parts
" milliseconds <br />");
document.write(
"Date: " + dateString + "<br />",
"Day: " + day + "<br />",
"Month: " + month + "<br />", // Note: date.js
"Year: " + year + "<br />",
"Time in milliseconds: " + timeMilliseconds + "<br />",
"Hour: " + hour + "<br />",
save the program as date.js
do {
count++;
sum = sum + (sum * count);
} while (count <= 50);
Develop a JavaScript page to demonstrate an if condition that greets the user with "Good Morning" if the time on their browser is less than 10.
<!DOCTYPE html>
<html>
<head>
<title>Time Greeting</title>
</head>
<body>
<script>
// Get the current time
var currentTime = new Date();
var currentHour = currentTime.getHours();
window.screen or just screen is a small information object about physical screen dimensions.
window.document or just document is the main object of the potentially visible (or better yet:
rendered) document object model/DOM.
Since window is the global object, you can reference any properties of it with just the property name -
so you do not have to write down window. - it will be figured out by the runtime.
window.document just means that document is a property of window. It's not an instance of window. window is the
global object. Every global variable is a property of the global object
• the constructor called is that of Object, which endows the new object with no
properties, although it does have access to some inherited methods.
• The variable my_object references the new object.
• Calls to constructors must include parentheses, even if there are no parameters
• The properties of an object can be accessed with dot notation, in which the first
word is the object name and the second is the property name.
• Properties are not actually variables—they are just the names of values. They are
used with object variables to access property values.
• properties are not variables, they are never declared.
• The number of properties in a JavaScript object is dynamic. At any time during
interpretation, properties can be added to or deleted from an object.
• A property for an object is created by assigning a value to its name.
• creates a new object, my_car, with two properties: make and model
The object referenced with my_car could be created with the following statement:
• var my_car = {make: "Ford", model: "Fusion"};
Objects can be nested, you can create a new object that is a property of my_car with
properties of its own, as in the following statements:
• my_car.engine = new Object();
• my_car.engine.config = "V6";
• my_car.engine.hp = 263;
the variables prop1 and prop2 both have the value "Ford".
If an attempt is made to access a property of an object that does
not exist, the value undefined is used.
A property can be deleted with delete, as in the following example:
• delete my_car.model;
Example:
for (var prop in my_car)
document.write("Name: ", prop, "; Value: ", my_car[prop], "<br />");
program on object//we are creating a custom
object called car
<html>
<body>
<p id="demo"></p>
<script>
var car= new Object();
car.type="maruthi";
car.speed="500"
car.engine=new Object();
car.engine.type="diesel"; //nested property
car.engine.xxx="llll";
document.getElementById("demo").innerHTML = car["speed"];
document.getElementById("demo").innerHTML = car.engine.type;
delete car.engine.xxx;
for(var i in car) //note new for loop
{
document.writeln("property is ", i, ";its value is",car[i],"<br>");
}
</script>
</body>
</html>
//or for loop can have contcatenation sign
{
document.writeln("property is "+i+" its value is"+car[i],"<br>");
document.writeln("<br>");
}
Output
diesel
property is type;its value ismaruthi
property is speed;its value is500
property is engine;its value is[object Object]
<!DOCTYPE html> // Display some data from the object:
<html> document.getElementById("demo").innerHTML = "The
car type is " + car1.type+"<br>"+ car1.model +"<br>"+
<body> car1.color
<h2>JavaScript Objects</h2>
<p id="demo"></p> document.writeln(car["type"]);// fiat
for(var i in car)
<p id="demo1"></p> {
<script> document.writeln("<br> property is "+i+ "<br> its value
// Create an object in two ways is <br>"+car[i]);
}
const car = {type:"Fiat",
model:"500", color:"white"};
var car1= new Object();
car1.type="Fiat1"; </script>
car1.model="600"; </body> 64
car1.color="red"; </html>
65
*Object Example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<p id="demo"></p>
<script>
// Create an object:
var car = {type:"Fiat", model:"500", color:"white"}; // this is alternate way of creating car object
</body>
</html>
output: Fiat
Object example
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<p id="demo"></p>
<script>
// Create an object:
var person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
</body>
</html>
*ARRAYS
EXAMPLE ON ARRAYS WITH ITS PROPERTIES
EXAMPLE ON ARRAYS WITH ITS METHODS
68
*Arrays javascript.com/learn/arrays
• Array objects, unlike most other JavaScript objects, can be created in two distinct ways.
• The usual way to create any object is to apply the new operator to a call to a constructor.
var my_list = new Array(1, 2, "three", "four");
var your_list = new Array(100);
• The second way to create an Array object is with a literal array value, which
is a list of values enclosed in brackets:
var my_list_2 = [1, 2, "three", "four"];
//try working out, : will join all the array contents with :
//ans is :join() returns an array as string //u can try joining with any characters like ‘and’
Mary:Murray:Murphy:Max
• reverse method: It reverses the order of the elements of the Array object through which
it is called. Eg var reversedstring =names.reverse();
• The sort method coerces the elements of the array to become strings if they
are not already strings and sorts them alphabetically.
For example: names.sort();
The value of names is now "Mary", "Max", "Murphy", "Murray".
• The concat method catenates its actual parameters to the end of the Array object on which it is called.
var names = new Array["Mary", "Murray", "Murphy", "Max"];
...
var new_names = names.concat("Moo", "Meow");
• The new_names array now has length 6, with the elements of names, along with
"Moo" and "Meow" as its fifth and sixth elements.
• The slice method: returning the part of the Array object specified by its parameters, which are used as
subscripts.
var list = [2, 4, 6, 8, 10];
var list2 = list.slice(1, 3);
• If slice is given just one parameter, the array that is returned has all the elements of the object,
starting with the specified index.
• var list = ["Bill", "Will", "Jill", "dill"];
• var listette = list.slice(2);
<script>
var arr=["AngularJS","Node.js","JQuery","Bootstrap"]
var arr5=[1,3,6,7,2]
var arr6 =arr5.sort(function(a,b){return b-a}); //sorting in descending order
document.writeln("after sortin");
document.writeln(arr6);
var result=arr.slice(1,2);//note:changes are not done in the original array,so store in new array
var result1=arr.concat("graphql","react");
document.writeln(result);
//following also does sorting in descending order using bubble sort
var ar = new Array(3,1,5,6);
Local Variables
• The scope of a variable is the range of statements over which it is visible. When
• JavaScript is embedded in an HTML document, the scope of a variable is the range
of lines of the document over which the variable is visible.
• Variables that are implicitly declared have global scope—that is, they are visible in
the entire HTML document.
• Variables that are
• Explicitly declared outside function definitions also have global scope. As stated
earlier, we recommend that all variables be explicitly declared.
Parameters
• The parameter values that appear in a call to a function are called actual
parameters.
• The parameter names that appear in the header of a function definition, which
correspond to the actual parameters in calls to the function, are called formal
parameters.
function fun1(my_list) {
var list2 = new Array(1, 3, 5);
my_list[3] = 14;
...
my_list = list2;
}
...
var list = new Array(2, 4, 6, 8)
fun1(list);
*FUNCTION CAN BE STORED AS VARIABLE
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions</h2>
<p>After a function has been stored in a
variable,
the variable can be used as a function:</p>
<p id="demo"></p>
<script>
const x = function (a, b) {return a * b};
document.getElementById("demo").innerHTML
= x(4, 3);
</script>
</body>
Example: function in a java script
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 />");
}
// A test driver for function params
params("Mozart");
params("Mozart", "Beethoven");
params("Mozart", "Beethoven", "Tchaikowsky");
pass a primitive value by reference
• There is no elegant way in JavaScript to pass a primitive value by reference.
• One inelegant way is to put the value in an array and pass the array, as in the following
script:
// Function by10
// Parameter: a number, passed as the first element
// of an array
// Returns: nothing
// Effect: multiplies the parameter by 10
function by10(a) {
a[0] *= 10;
}
...
var x;
var listx = new Array(1);
...
listx[0] = x;
by10(listx);
x = listx[0];
• Another way to have a function change the value of a primitive-type actual
parameter is to have the function return the new value as follows:
function by10_2(a) {
return 10 * a;
}
var x;
...
x = by10_2(x);
Example:
num_list.sort(num_order);
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions</h2>
<p>Global functions automatically become window methods. Invoking myFunction() is the same as invoking
window.myFunction().</p>
<p id="demo"></p>
<script>
function myFunction(a, b) {
return a * b;
}
document.getElementById("demo").innerHTML = window.myFunction(10, 2);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions</h2>
<p>In HTML the value of <b>this</b>, in a global function, is the window object.</p>
<p id="demo"></p>
<script>
let x = myFunction();
function myFunction() {
return this;
}
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
*Invoking functions as method
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions</h2>
<p id="demo"></p>
<script>
const myObject =
{
firstName:"John",
lastName: "Doe",
fullName: function() {
return this.firstName + " " + this.lastName;
}
}
document.getElementById("demo").innerHTML = myObject.fullName();
document.getElementById("demo").innerHTML=myObject.firstName;
</script>
</body>
</html>
The second method of creating a JavaScript object is to use the constructor function
. We define an object type without any specific values. Then, we create new object instances and populate each of them
Below, we can see the same userProfile001 object defined by using a constructor function called function User(). The
constructor creates an object type called User(). Then, we create a new object instance called userProfile001, using the new
operator. The constructor function contains three this statements that define the three properties with empty values. The
92
Constructors
93
Constructors
• JavaScript constructors are special functions that create and initialize the properties of newly created objects
• Every new expression must include a call to a constructor whose name is the same as that of the object being
created.
<script>
function car(new_make, new_model, new_year)
{
this.make = new_make;
this.model = new_model;
this.year = new_year;
this.display=function display_car() {
document.write("Car make: ", this.make, "<br/>");
document.write("Car model: ", this.model, "<br/>");
document.write("Car year: ", this.year, "<br/>");
} }
}
my_car = new car("Ford", "Fusion", "2012");
</script>
• If a method is to be included in the object, it is initialized the same way as if it were a data property
example2
95
example 3
96
Example 4 Invoking a Function with a Function Constructor
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions</h2>
<p>In this example, myFunction is a function constructor:</p>
<p id="demo"></p>
<script>
function myFunction(arg1, arg2) {
this.firstName = arg1;
this.lastName = arg2;
return this;
}
</body>
</html>
More Example on functions
<!DOCTYPE html>
<html> <!DOCTYPE html>
<body> <html>
<body>
<h2>JavaScript Functions</h2>
<p>JavaScript has an built-in function constructor.</p> <h2>JavaScript Functions</h2>
<p id="demo"></p>
<p id="demo"></p>
<script>
const myFunction = new Function("a", "b", "return a * <script>
b"); const myFunction = function (a, b)
document.getElementById("demo").innerHTML = {return a * b}
myFunction(4, 3); document.getElementById("demo").in
</script> nerHTML = myFunction(4, 3);
</body> </script>
</html>
</body>
</html>
more egs:
<<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Functions</h2>
<p>Finding the largest number.</p>
<p id="demo"></p>
<script>
function findMax() {
let max = Number.NEGATIVE_INFINITY;
document.writeln(Number.NEGATIVE_INFINITY);
//let max=-Infinity;
for(let i = 0; i < arguments.length; i++) {
if (arguments[i] > max) {
max = arguments[i];
}
}
return max;
}
</body>
Arrow function
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
//document.getElementById("demo").innerHTML = x(5, 5);
const x = (x, y) => {return x * y };
document.getElementById("demo").innerHTML = x(5, 5);
</script>
</body>
</html>
The following line must then be added to the car constructor:
this.display = display_car;
Now the call my_car.display() will produce the following output:
Car make: Ford
Car model: Fusion
Car year: 2012
Extra program to practice-Table program using javascript
<html>
<head>
<script>
document.write("<table border='1'><tr><th colspan='3'>"+ "NUMBERS FROM 0 TO 10 WITH THEIR
SQUARES AND CUBES" +"</th></tr>" );
document.write("<tr><th>Number</th><th>Square</th><th>Cube</th></tr>");
for(var n=1; n<=10; n++)
{
document.write( "<tr><td>" + n + "</td><td>" + n*n +
"</td><td>" +
n*n*n + "</td></tr>" ) ;
}
document.write( "</table>" );
</script>
</head>
</html>
*DOM-WHAT IS DOM
* WHAT ARE EVENTS(DIFFERENT
TYPES OF EVENTS
* REGISTERING AN EVENT
• JavaScript binding to the DOM, the elements of a document are objects, with
both data and operations. The data are called properties, and the operations
are,
naturally, called methods.
• In most cases, the property names in JavaScript are the same as their
corresponding attribute names in HTML.
Document Object Model :
• DOM is an Application Programming Interface (API) that defines an
interface between HTML documents and application programs.
• Documents in the DOM have a treelike structure, but there can be more
than one tree in a document (although that is unusual).
• Because the DOM is an abstract interface, it does not dictate that
documents be implemented as trees or collections of trees.
<!DOCTYPE html>
<!-- table2.html
A simple table to demonstrate DOM trees
-->
<html lang = "en">
<head>
<title> A simple table </title>
<meta charset = "utf-8" />
</head>
<body>
<table>
<tr>
<th> </th>
<th> Apple </th>
<th> Orange </th>
</tr>
<tr>
<th> Breakfast </th>
<td> 0 </td>
<td> 1 </td>
</tr>
</table>
</body>
</html>
Events and Event Handling:
• Event-driven: code executed resulting to user or browser
action.
• Event: a notification that something specific occurred --
by browser or user.
• Event handler: a script implicitly executed in response to event
occurrence.
• Registration: the process of connecting event handler to
event.
• Events are JavaScript objects --> names are case sensitive, all use lowercase
only.
(Method write should never be used in event handler. May cause document
to be written over.)
• JavaScript events associated with HTML tag attributes which can be used to
connect to event-handlers
11
• JavaScript's interaction with HTML is handled through events that occur
when the user or the browser manipulates a page.
• When the page loads, it is called an event. When the user clicks a button,
that click too is an event,Other examples include events like pressing any
key, closing a window, resizing a window, etc.
• Developers can use these events to execute JavaScript coded responses, which
cause buttons to close windows, messages to be displayed to users, data to be
validated, and virtually any other type of response imaginable.
• Events are a part of the Document Object Model DOM Level 3 and every
118
• HTML element contains a set of events which can trigger
JavaScript Code.
<p>When you leave the input field, a function is triggered which transforms the input text to upper
case.</p>
<script>
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</body>
</html>
REGISTERING AN EVENT HANDLER(three ways
we will c)
• There are different ways to register an event handler in the DOM 0
First Way :
• event model. One of these is by assigning the event handler script to an
event tag attribute, as in the following example:
• An event handler function could also be registered by assigning its name to the
associated event property on the button object, as in the following example:
• document.getElementById("myButton").onclick =myButtonHandler;
• This statement must follow both the handler function and the form element so
that JavaScript has seen both before assigning the property.
• The name of the handler function is assigned to the property—it is neither a
string nor a call to the function.
• Third way is via addevent listener
Third way is ADDEVENTLISTENER
127
Example on the three way of registering an event is seen on the next
slide.
128
Event handler example [WE CAN REGISTER AN EVENT BY
USING ON[EVENT] -EG: ONCLICK OR ADDEVENTLISTENER
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript addEventListener()</h2>
<p>This example uses the addEventListener() method to attach a click event to a button.</p>
//document.getElementById("myBtn").onclick=displayDate;
document.getElementById("myBtn").addEventListener("click", displayDate);
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
</body>
Following slides are examples on various events
130
Example :Handling Events from Text Box and Password Elements:
• Text boxes and passwords can create four different events: blur, focus,
change
and select.
For ex:
• Suppose JavaScript is used to compute the total cost of an order and display
it to the customer before the order is submitted to the server for processing.
An unscrupulous user may be tempted to change the total cost before
submission, thinking that somehow an altered (and lower) price would not
be noticed at the server end.
• Such a change to a text box can be prevented by an event handler that blurs
the text box every time the user attempts to put it in focus.
• Blur can be forced on an element with the blur method.
• The HTMLElement.blur() method removes keyboard focus from the current element.
(Eg,this.blur())
example on onfocus and onclick
132
<!DOCTYPE html>
<html lang = "en">
<head>
<title> nochange.html </title>
<meta charset = "utf-8" />
<script type = "text/javascript" src = "nochange.js" >
</script>
<style type = "text/css">
td, th, table {border: thin solid black}
</style>
</head>
<body>
<form action = "">
<h3> Coffee Order Form </h3>
<!-- A bordered table for item orders -->
<table>
<!-- First, the column headings -->
<tr>
<th> Product Name </th>
<th> Price </th>
<th> Quantity </th>
</tr>
<!-- Now, the table data entries -->
<tr>
<th> French Vanilla (1 lb.) </th>
<td> $3.49 </td>
<td> <input type = "text" id = "french"
size ="2" /> </td>
</tr>
<tr>
<th> Hazlenut Cream (1 lb.) </th>
<td> $3.95 </td>
<td> <input type = "text" id = "hazlenut"
size = "2" /> </td>
</tr>
<tr>
<th> Colombian (1 lb.) </th>
<td> $4.59 </td>
<td> <input type = "text" id = "colombian"
size = "2" /></td>
</tr>
</table>
<!-- Button for precomputation of the total cost -->
<p>
<input type = "button" value = "Total Cost"
onclick = "computeCost();" />
<input type = "text" size = "5" id = "cost"
onfocus = "this.blur();" />
</p>
<!-- The submit and reset buttons -->
<p>
<input type = "submit" value = "Submit Order" />
<input type = "reset" value = "Clear Order Form" />
</p>
</form>
</body>
nochange.js:
function computeCost() {
var french = document.getElementById("french").value;
var hazlenut = document.getElementById("hazlenut").value;
var colombian = document.getElementById("colombian").value;
document.getElementById("cost").value =
totalCost = french * 3.49 + hazlenut * 3.95 +colombian * 4.59;
}
<!DOCTYPE html>
<!-- pswd_chk.html
A document for pswd_chk.ps
Creates two text boxes for passwords
-->
<html lang = "en">
<head>
<title> Illustrate password checking> </title>
<meta charset = "utf-8" />
<script type = "text/javascript" src = "pswd_chk.js" >
</script>
</head>
<body>
<h3> Password Input </h3>
<form id = "myForm" action = "" >
<p>
example on password validation
139
<label> Your password
<input type = "password" id = "initial"
size = "10" />
</label>
<br /><br />
<label> Verify password
<input type = "password" id = "second"
size = "10" />
</label>
<br /><br />
<input type = "reset" name = "reset" />
<input type = "submit" name = "submit" />
</p>
</form>
<!-- Script for registering the event handlers -->
<script type = "text/javascript" src = "pswd_chkr.js">
</script>
</body>
</html>
// pswd_chk.js
// An example of input password checking using the submit
// event
// The event handler function for password checking
function chkPasswords() {
var init = document.getElementById("initial");
var sec = document.getElementById("second");
if (init.value == "") {
alert("You did not enter a password \n" +
"Please enter one now");
return false;
}
if (init.value != sec.value) {
alert("The two passwords you entered are not the same \n" +
"Please re-enter both now");
return false;
} else
return true;
}
pswd_chkr.js
// Register the event handlers for pswd_chk.html
document.getElementById("second").onblur = chkPasswords;
document.getElementById("myForm").onsubmit =
chkPasswords;
• Figure 1 shows a browser display of pswd_chk.html after the two
password
elements have been input but before Submit Query has been clicked.
• Figure 2 shows a browser display that results from pressing the Submit
• Query button on pswd_chk.html after different passwords have been
entered
onclick Event Type
• This is the most frequently used event type which occurs when a user clicks the
left button of his mouse.
• One attribute can appear in several different tags:
e.g. onClick can be in <a> and <input>
• HTML element get focus:
1. When user puts mouse cursor over it and presses the left button
2. When user tabs to the element
3. By executing the focus method
4. Element get blurred when another element gets focus
• Event handlers can be specified two ways
1. Assigning the event handler script to an event tag attribute
onClick = "alert('Mouse click!');"
onClick = "myHandler();
2. Assigning them to properties of JavaScript object associated with HTML elements.
• The load event: the completion of loading of a document by browser
• The onload attribute of <body> used to specify event handler:
• The unload event: used to clean up things before a document is unloaded.
145
Example:onclick
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function sayHello(){}
</script>
</head>
<body>
<p>Click the following button and see result</p>
<form>
<input type="button" onclick="sayHello()" value="Say
Hello" />
</form>
</body>
</html> 14
onSubmit Event Type:
<script type="text/javascript">
function validate(){
if ((document.example2.naming.value=="") || (document.example2.feed.value=="")){
alert("You must fill in all of the required fields!")
return false
}
else
return true
}
</script>
<html>
<head>
<script type="text/javascript">
function validate()
</script>
</head>
<body>
.......
</form>
</body>
</html>
onmouseover and
onmouseout :
• These two event types will help you create nice effects with images or
even with text as well.
• The onmouseover event triggers when you bring your
mouse over any element and the onmouseout triggers
when you move your mouse out from that element.
• Try the following example.
15
<html>
<body>
<p>Bring your mouse inside the division to see the result:</p>
<div onmouseover="over()" onmouseout="out()">
<h2 id="l1"> This is inside the division </h2>
</div>
<script >
function over()
{
document.getElementById("l1").innerHTML="Welcome ABC";
}
function out()
{
document.getElementById("l1").innerHTML="";
}
</script>
</body>
</html>
15
Focus & Blur Event Example:
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
</head>
<body>
<h1>Hello How Are You...?</h1>
<form>
Click This Button<br/>
<input type="button" value="Click Me!"
onclick="myFun()"/><br/>
<input type="text" id="username" onfocus="this.blur()"/><br/>
</form> [fig.1 Before Click On That Button]
<script type="text/javascript">
function myFun()
{
document.getElementById("username").value="Dhruv";
}
</script>
</body>
</html>
15
Third way of registering an event
3.addEventListener:
• The Event Target method addEventListener() sets up a function that
will be called whenever the specified event is delivered to the target.
• Common targets are Element, Document, and Window, but the target may be
any object that
supports events (such as XML Http Request).
15
The addEventListener() method attaches an event handler to the specified element.
The addEventListener() method attaches an event handler to an element without overwriting existing event
handlers.
You can add many event handlers of the same type to one element, i.e two "click" events.
You can add event listeners to any DOM object not only HTML elements. i.e the window object.
The addEventListener() method makes it easier to control how the event reacts to bubbling.
When using the addEventListener() method, the JavaScript is separated from the HTML markup, for better
readability and allows you to add event listeners even when you do not control the HTML markup.
You can easily remove an event listener by using the removeEventListener() method.
Syntax
15
removeEventListener:
15
Syntax
target.removeEventListener(type, listener[, options]);
target.removeEventListener(type, listener[,
useCapture]);
15
<!DOCTYPE html>
<html>
<head><title>Display Page</title></head> An Example of onclick
<body>
<hr color="orange" />
<center><h1 id="htag">Welcome To ADIT</h1></center>
<hr color="blue" />
<center><button type="button" onclick="Change()">Change</button>
<button type="button" onclick="Hide()">Hide</button>
<button type="button" onclick="Display()">Display</button>
<button type="button" onclick="ChangeColor()">Color Change</button></center>
<hr color="green" />
<script type="text/javascript">
function Change()
{ document.getElementById("htag").innerHTML="Welcome ABC"; }
function Display()
{ document.getElementById("htag").style.display="block"; }
function Hide()
{ document.getElementById("htag").style.display="none"; }
function ChangeColor()
{ document.getElementById("htag").style.color="blue"; }
</script>
</body>
</html>
15
Event handler example
revise :Event handler example [WE CAN REGISTER AN EVENT
BY USING ON[EVENT] EG ONCLICK OR ADDEVENTLISTENER
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript addEventListener()</h2>
<p>This example uses the addEventListener() method to attach a click event to a button.</p>
//document.getElementById("myBtn").onclick=displayDate;
document.getElementById("myBtn").addEventListener("click", displayDate);
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}
</script>
</body>
</html>
using addEventListeneter calling two
functions on the element
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript addEventListener()</h2>
<p>This example uses the addEventListener() method to add two click events to the same button.</p>
<script>
var x = document.getElementById("myBtn");
x.addEventListener("click", myFunction);
x.addEventListener("click", someOtherFunction);
function myFunction() {
alert ("Hello World!");
}
function someOtherFunction() {
alert ("This function was also executed!");
}
</script>
</body>
</html>
addEventListener and removeEventListener
<!DOCTYPE html>
<html>
<head>
<style>
#myDIV {
background-color: coral;
border: 1px solid;
padding: 50px;
color: white;
font-size: 20px;
}
</style>
</head>
<body>
<h2>JavaScript removeEventListener()</h2>
<div id="myDIV">
<p>This div element has an onmousemove event handler that displays a random number every time you move your mouse inside this orange field.</p>
<p>Click the button to remove the div's event handler.</p>
<button onclick="removeHandler()" id="myBtn">Remove</button>
</div>
<p id="demo"></p>
<script>
document.getElementById("myDIV").addEventListener("mousemove", myFunction);
function myFunction() {
document.getElementById("demo").innerHTML = Math.random();
}
function removeHandler() {
document.getElementById("myDIV").removeEventListener("mousemove", myFunction);
}
</script>
</body>
</html>
example :focus and blur on EventListener
<!DOCTYPE html>
<html>
<body>
<p>When you enter the input field (child of FORM), a function is triggered which sets the background color to yellow. When you leave the input field, a function
is triggered which removes the background color.</p>
<form id="myForm">
<input type="text" id="myInput">
</form>
<script>
var x = document.getElementById("myForm");
x.addEventListener("focus", myFocusFunction, true);
x.addEventListener("blur", myBlurFunction, true);
function myFocusFunction() {
document.getElementById("myInput").style.backgroundColor = "yellow";
}
function myBlurFunction() {
document.getElementById("myInput").style.backgroundColor = "";
}
</script>
</body>
</html>
Output
addEventListener on window object
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript addEventListener()</h2>
<p>Try resizing this browser window to trigger the "resize" event handler.</p>
<p id="demo"></p>
<script>
window.addEventListener("resize", function(){
document.getElementById("demo").innerHTML = Math.random();
});
</script>
</body>
</html>
A brief Introduction on Regular Expressions
167
PATTERN MATCHING BY USING
REGULAR EXPRESSIONS :
• JavaScript has powerful pattern-matching capabilities based on regular expressions.
i. RegExp object
ii. Methods of the String object.
• The simplest pattern-matching method is search, which takes a pattern as a parameter.
• The search method returns the position in the String object (through which it is called) at which
https://www.w3schools.com/js/js_regexp.asp
var str = "Rabbits are furry";
var position = str.search(/bits/);
if (position >= 0)
document.write("'bits' appears in position", position,
"<br />");
else
document.write("'bits' does not appear in str <br />");
Output:
'bits' appears in
position 3
……….end of module 3……….
172