Unit 2 Notes
Unit 2 Notes
INTRODUCTION
Javascript is a dynamic computer programming language. It is lightweight
and most commonly used as a part of web pages, whose implementations allow
client-side script to interact with the user and make dynamic pages. It is an
interpreted programming language with object-oriented capabilities.
JavaScript was first known as LiveScript, but Netscape changed its name to
JavaScript, possibly because of the excitement being generated by Java.
JavaScript made its first appearance in Netscape 2.0 in 1995 with the name
LiveScript. The general-purpose core of the language has been embedded in
Netscape, Internet Explorer, and other web browsers.
Client-side JavaScript
Client-side JavaScript is the most common form of the language. The script should
be included in or referenced by an HTML document for the code to be interpreted
by the browser.
It means that a web page need not be a static HTML, but can include programs
that interact with the user, control the browser, and dynamically create HTML
content.
The JavaScript client-side mechanism provides many advantages over traditional
CGI server-side scripts. For example, you might use JavaScript to check if the
user has entered a valid e-mail address in a form field.
The JavaScript code is executed when the user submits the form, and only if all
the entries are valid, they would be submitted to the Web Server.
JavaScript can be used to trap user-initiated events such as button clicks, link
navigation, and other actions that the user initiates explicitly or implicitly.
Advantages of JavaScript
• Less server interaction − You can validate user input before sending the page
off to the server. This saves server traffic, which means less load on your server.
• Immediate feedback to the visitors − They don't have to wait for a page reload
to see if they have forgotten to enter something.
• Increased interactivity − You can create interfaces that react when the user
hovers over them with a mouse or activates them via the keyboard.
• Richer interfaces − You can use JavaScript to include such items as drag-and-
drop components and sliders to give a Rich Interface to your site visitors.
22UAD502 FULL STACK DEVELOPMENT UNIT II
Limitations of JavaScript
• Client-side JavaScript does not allow the reading or writing of files. This has
been kept for security reason.
• JavaScript cannot be used for networking applications because there is no such
support available.
• JavaScript doesn't have any multithreading or multiprocessor capabilities.
JavaScript can be implemented using JavaScript statements that are placed
within the<script>... </script> HTML tags in a web page.
You can place the <script> tags, containing your JavaScript, anywhere within you
web page, but it is normally recommended that you should keep it within the
<head> tags.
The <script> tag alerts the browser program to start interpreting all the text
between these tags as a script. A simple syntax of your JavaScript will appear as
follows.
The script tag takes two important attributes –
• Language − This attribute specifies what scripting language you are using.
Typically, its value will be javascript. Although recent versions of HTML (and
XHTML, its successor) have phased out the use of this attribute.
• Type − This attribute is what is now recommended to indicate the scripting
language in use and its value should be set to "text/javascript".
So your JavaScript segment will look like −
<scriptlanguage="javascript"type="text/javascript">
JavaScript code
</script>
22UAD502 FULL STACK DEVELOPMENT UNIT II
<head>
</head>
<body>
<script type="text/javascript">
<!--
22UAD502 FULL STACK DEVELOPMENT UNIT II
document.write("Hello World")
//-->
</script>
<p>This is web page body </p>
</body>
</html>
This code will produce the following results −
JavaScript in <body> and <head> Sections
You can put your JavaScript code in <head> and <body> section altogether as
follows −
<html>
<head>
<script type="text/javascript">
<!--
FunctionsayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
</body>
</html>
This code will produce the following result −
JavaScript in External File
As you begin to work more extensively with JavaScript, you will be likely to find
that there are cases where you are reusing identical JavaScript code on multiple
pages of a site.
You are not restricted to be maintaining identical code in multiple HTML files.
The script tag provides a mechanism to allow you to store JavaScript in an
external file and then include it into your HTML files.
22UAD502 FULL STACK DEVELOPMENT UNIT II
Here is an example to show how you can include an external JavaScript file in
your HTML code using script tag and its src attribute.
<html>
<head>
<script type="text/javascript" src="filename.js" ></script>
</head>
<body>
.......
</body>
</html>
To use JavaScript from an external file source, you need to write all your
JavaScript source code in a simple text file with the extension ".js" and then
include that file as shown above.
For example, you can keep the following content in filename.js file and then you
can usesayHello function in your HTML file after including the filename.js file.
FunctionsayHello() {
alert("Hello World")
}
JAVASCRIPT OUTPUT
JavaScript does NOT have any built-in print or display functions.
JavaScript Display Possibilities
JavaScript can "display" data in different ways:
• Writing into an alert box, using window.alert().
• Writing into the HTML output using document.write().
• Writing into an HTML element, using innerHTML.
• Writing into the browser console, using console.log().
Using window.alert()
You can use an alert box to display data:
<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
window.alert(5 + 6);
</script>
</body></html>
22UAD502 FULL STACK DEVELOPMENT UNIT II
Using document.write()
For testing purposes, it is convenient to use document.write():
<!DOCTYPE html>
<html>
<body>
<script>
document.write(5 + 6);
</script>
</body>
</html>
Using document.write() after an HTML document is fully loaded, will delete all
existing HTML:
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Using innerHTML
To access an HTML element, JavaScript can use
the document.getElementById(id) method.
The id attribute defines the HTML element. The innerHTML property defines
the HTML content:
<!DOCTYPE html>
<html>
<body>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
Using console.log()
In your browser, you can use the console.log() method to display data.
Activate the browser console with F12, and select "Console" in the menu.
Example
<!DOCTYPE html>
<html>
<body>
<script>
console.log(5 + 6);
</script>
</body>
</html>
SYNTAX OF JAVASCRIPT
JavaScript syntax is the set of rules, how JavaScript programs are constructed.
A computer program is a list of "instructions" to be "executed" by the
computer.
In a programming language, these program instructions are
called statements.JavaScript is a programming language.
JavaScript statements are separated by semicolons.
var x = 5;
var y = 6;
var z = x + y;
Statements
JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.
Values
22UAD502 FULL STACK DEVELOPMENT UNIT II
The JavaScript syntax defines two types of values: Fixed values and variable
values.
Fixed values are called literals. Variable values are called variables.
Variables
In a programming language, variables are used to store data values.
JavaScript uses the var keyword to define variables.
An equal sign is used to assign values to variables.
In this example, x is defined as a variable. Then, x is assigned (given) the value
6:
var x;
x = 6;
Operators
JavaScript uses an assignment operator ( = ) to assign values to variables:
var x = 5;
var y = 6;
Expressions
An expression is a combination of values, variables, and operators, which
computes to a value.
The computation is called an evaluation.
For example, 5 * 10 evaluates to 50:
5 * 10
Expressions can also contain variable values:
x * 10
The values can be of various types, such as numbers and strings.
For example, "John" + " " + "Doe", evaluates to "John Doe":
"John" + " " + "Doe"
Keywords
Keywords are used to identify actions to be performed.The var keyword tells
the browser to create a new variable:
var x = 5 + 6;
var y = x * 10;
Comments in JavaScript
JavaScript supports both C-style and C++-style comments, Thus −
• Any text between a // and the end of a line is treated as a comment and is
ignored by JavaScript.
22UAD502 FULL STACK DEVELOPMENT UNIT II
• Any text between the characters /* and */ is treated as a comment. This may
span multiple lines.
• JavaScript also recognizes the HTML comment opening sequence <!--.
JavaScript treats this as a single-line comment, just as it does the // comment.
• The HTML comment closing sequence --> is not recognized by JavaScript so it
should be written as //-->.
Identifiers
Identifiers are names.
In JavaScript, identifiers are used to name variables (and keywords, and
functions, and labels).
The rules for legal names are much the same in most programming languages.
In JavaScript, the first character must be a letter, an underscore (_), or a dollar
sign ($).
Subsequent characters may be letters, digits, underscores, or dollar signs.
FUNCTIONS
• A function is a block of code designed to perform a particular task.
• A function is a group of reusable code which can be called anywhere in your
program. This eliminates the need of writing the same code again and again. It
helps programmers in writing modular codes. Functions allow a programmer to
divide a big program into a number of small and manageable functions.
• A JavaScript function is executed when "something" invokes it (calls it).
Syntax
A JavaScript function is defined with the function keyword, followed by
a name, followed by parentheses ().
function name(parameter1, parameter2, parameter3) {
code to be executed
}
Function parameters are the names listed in the function
definition.Function arguments are the real values received by the function when
it is invoked.Inside the function, the arguments are used as local variables.
function myFunction(p1, p2) {
return p1 * p2; // The function returns the product of p1 and p2
}
Function Invocation
The code inside the function will execute when "something" invokes (calls) the
function:
• When an event occurs (when a user clicks a button)
• When it is invoked (called) from JavaScript code
• Automatically (self invoked)
22UAD502 FULL STACK DEVELOPMENT UNIT II
<html><head>
<script type="text/javascript">
FunctionsayHello(name, age)
{
document.write (name + " is " + age + " years old.");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="sayHello('Zara', 7)" value="Say Hello">
</form>
<p>Use different parameters inside the function and then try...</p>
</body>
</html>
return Statement
A JavaScript function can have an optional return statement. This is required if
you want to return a value from a function. This statement should be the last
statement in a function.
<html>
<head>
<script type="text/javascript">
function concatenate(first, last)
{
var full;
full = first + last;
return full;
}
functionsecondFunction()
{
var result;
result = concatenate('Zara', 'Ali');
document.write (result );
}
</script>
</head>
<body>
22UAD502 FULL STACK DEVELOPMENT UNIT II
</body>
</html>
Nested Functions
Function inside another function is known as Nested Functions.
<html>
<head>
<script type="text/javascript">
<!--
function hypotenuse(a, b) {
function square(x) { return x*x; }
returnMath.sqrt(square(a) + square(b));
}
functionsecondFunction(){
var result;
result = hypotenuse(1,2);
document.write( result );
}
//-->
</script>
</head>
<body>
<form>
<input type="button" onclick="secondFunction()" value="Call Function">
</form>
</body>
</html>
Function Constructors
The function statement is not the only way to define a new function; you can define
your function dynamically using Function() constructor along with the new
operator.
Note − Constructor is a terminology from Object Oriented Programming. You
may not feel comfortable for the first time, which is OK.
22UAD502 FULL STACK DEVELOPMENT UNIT II
Syntax
Following is the syntax to create a function using Function( ) constructor along
with thenew operator.
<script type="text/javascript">
Var variablename = new Function(Arg1, Arg2..., "Function Body");
</script>
The Function() constructor expects any number of string arguments. The last
argument is the body of the function – it can contain arbitrary JavaScript
statements, separated from each other by semicolons.
Notice that the Function() constructor is not passed any argument that specifies a
name for the function it creates. The unnamed functions created with the
Function() constructor are called anonymous functions.
<html>
<head>
<script type="text/javascript">
<!--
Var func = new Function("x", "y", "return x*y;");
functionsecondFunction(){
var result;
result = func(10,20);
document.write( result );
}
//-->
</script>
</head>
<body>
<form>
<input type="button" onclick="secondFunction()" value="Call Function">
</form></body></html>
Function literals
Function literals which is another new way of defining functions. A function
literal is an expression that defines an unnamed function.
Syntax
The syntax for a function literal is much like a function statement, except that it
is used as an expression rather than a statement and no function name is required.
<script type="text/javascript">
var variablename = function(Argument List){
Function Body
};
22UAD502 FULL STACK DEVELOPMENT UNIT II
</script>
Syntactically, you can specify a function name while creating a literal function
as follows.
<script type="text/javascript">
Var variablename = function FunctionName(Argument List){
Function Body
};
</script>
But this name does not have any significance, so it is not worthwhile.
<html>
<head>
<script type="text/javascript">
var func = function(x,y){ return x*y };
functionsecondFunction(){
var result;
result = func(10,20);
document.write( result );
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type="button" onclick="secondFunction()" value="Call Function">
</form>
</body></html>
OBJECTS
Objects are composed of attributes. If an attribute contains a function, it is
considered to be a method of the object, otherwise the attribute is considered a
property.
In real life, a car is an object.
A car has properties like weight and color, and methods like start and stop:
All cars have the same properties, but the property values differ from car to car.
All cars have the same methods, but the methods are performed at different times.
var car = "Fiat";
Objects are variables too. But objects can contain many values.
var car = {type:"Fiat", model:500, color:"white"};
Properties
22UAD502 FULL STACK DEVELOPMENT UNIT II
Methods are useful for everything from displaying the contents of the object to
the screen to performing complex mathematical operations on a group of local
properties and parameters.
User-Defined Objects
All user-defined objects and built-in objects are descendants of an object called
Object.
The new Operator
The new operator is used to create an instance of an object. To create an object,
the new operator is followed by the constructor method.
In the following example, the constructor methods are Object(), Array(), and
Date(). These constructors are built-in JavaScript functions.
var employee = new Object();
var books = new Array("C++", "Perl", "Java");
var day = new Date("August 15, 1947");
The Object() Constructor
A constructor is a function that creates and initializes an object. JavaScript
provides a special constructor function called Object() to build the object. The
return value of theObject() constructor is assigned to a variable.
The variable contains a reference to the new object. The properties assigned to the
object are not variables and are not defined with the var keyword.
<html><head>
<title>User-defined objects</title>
<script type="text/javascript">
var book = new Object(); // Create the object
book.subject = "C++"; // Assign properties to the object
book.author = "Ira Pohl"; OUTPUT:
</script>
</head> Book name is : C++
<body>
Book author is : Ira Pohl
<script type="text/javascript">
document.write("Book name is : " + book.subject + "<br>");
document.write("Book author is : " + book.author + "<br>");
</script>
</body></html>
Example 2:
<html><head>
<title>User-defined objects</title>
<script type="text/javascript">
function book(title, author){
this.title = title;
22UAD502 FULL STACK DEVELOPMENT UNIT II
this.author = author;
}
</script> OUTPUT:
</head>
Book name is : C++
<body>
<script type="text/javascript"> Book author is : Ira Pohl
varmyBook = new book("C++", "Ira Pohl");
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
</script>
</body></html>
Defining Methods for an Object
<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
// Define a function which will work as a method
FunctionaddPrice(amount){
this.price = amount;
}
function book(title, author){
this.title = title;
this.author = author;
this.addPrice = addPrice; // Assign that method as property.
}
</script> OUTPUT:
</head> Book name is : C++
<body>
<script type="text/javascript"> Book author is : Ira Pohl
varmyBook = new book("C++", "Ira Pohl"); Book priceis : 100
myBook.addPrice(100);
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
document.write("Book price is : " + myBook.price + "<br>");
</script></body></html>
NUMBER OBJECT
The Number object represents numerical date, either integers or floating-point
numbers. In general, you do not need to worry about Number objects because
22UAD502 FULL STACK DEVELOPMENT UNIT II
</body></html>
ARRAY OBJECT
The Array object lets you store multiple values in a single variable. It stores a
fixed-size sequential collection of elements of the same type. An array is used to
store a collection of data, but it is often more useful to think of an array as a
collection of variables of the same type.
Syntax
var fruits = new Array( "apple", "orange", "mango" );
OR
var fruits = [ "apple", "orange", "mango" ]; //easiest method - literal
You will use ordinal numbers to access and to set values inside an array as
follows.
fruits[0] is the first element
fruits[1] is the second element
fruits[2] is the third element
Method Description
concat() Joins two or more arrays, and returns a copy of the joined arrays
indexOf() Search the array for an element and returns its position
join() Joins all elements of an array into a string
lastIndexOf() Search the array for an element, starting at the end, and returns its
pop() Removes the last element of an array, and returns that element
push() Adds new elements to the end of an array, and returns the new
reverse() Reverses the order of the elements in an array
shift() Removes the first element of an array, and returns that element
slice() Selects a part of an array, and returns the new array
sort() Sorts the elements of an array
splice() Adds/Removes elements from an array
toString() Converts an array to a string, and returns the result
unshift() Adds new elements to the beginning of an array, and returns the
22UAD502 FULL STACK DEVELOPMENT UNIT II
Example:
<!DOCTYPE html><html>
<body>
<button onclick="myNumber()">Sorting of Numbers</button>
<p id="demo"></p>
<p id="demo1"></p>
<button onclick="myFruits()">Sorting of Alphabets</button>
<p id="demo2"></p>
<button onclick="myList()">Listing Fruits</button>
<p id="demo3"></p>
<script>
functionmyFruits() {
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Lemon"); //to add an element to the array
fruits[fruits.length] = "Pomegranate"
fruits[6]="Grapes"
document.getElementById("demo2").innerHTML = fruits;
fruits.sort();
fruits.reverse();
document.getElementById("demo2").innerHTML = fruits;
}
functionmyNumber() {
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});
document.getElementById("demo").innerHTML = points;
points.sort(function(a, b){return b-a});
document.getElementById("demo1").innerHTML = points;
functionmyList()
{
var index;
var text = "<ul>";
var fruits = ["Banana", "Orange", "Apple", "Mango"];
22UAD502 FULL STACK DEVELOPMENT UNIT II
DATE OBJECT
Method Description
getDate() Returns the day of the month (from 1-31)
getDay() Returns the day of the week (from 0-6)
getFullYear() Returns the year (four digits)
getHours() Returns the hour (from 0-23)
getMilliseconds() Returns the milliseconds (from 0-999)
getMinutes() Returns the minutes (from 0-59)
getMonth() Returns the month (from 0-11)
getSeconds() Returns the seconds (from 0-59)
22UAD502 FULL STACK DEVELOPMENT UNIT II
<!DOCTYPE html><html>
<body>
<button onclick="myFunction()">Print Date</button>
<script>
FunctionmyFunction() {
22UAD502 FULL STACK DEVELOPMENT UNIT II
MATH OBJECT
The Math object allows you to perform mathematical tasks on numbers.
Constants
Math.E // returns Euler's number
Math.PI // returns PI
Math.SQRT2 // returns the square root of 2
Math.SQRT1_2 // returns the square root of 1/2
Math.LN2 // returns the natural logarithm of 2
Math.LN10 // returns the natural logarithm of 10
Math.LOG2E // returns base 2 logarithm of E
Math.LOG10E // returns base 10 logarithm of E
Method Description
abs(x) Returns the absolute value of x
acos(x) Returns the arccosine of x, in radians
asin(x) Returns the arcsine of x, in radians
22UAD502 FULL STACK DEVELOPMENT UNIT II
<!DOCTYPE html>
<html>
<body>
<script>
FunctionmyFunction() {
document.write(Math.min(0, 150, 30, 20, -8, -200));
document.write("<br>");
document.write(Math.max(0, 150, 30, 20, -8, -200));
document.write("<br>");
document.write(Math.random());
22UAD502 FULL STACK DEVELOPMENT UNIT II
document.write("<br>");
document.write(Math.round(4.7888));
document.write("<br>");
document.write(Math.SQRT2);
document.write("<br>");
document.write(Math.SQRT1_2);
document.write("<br>");
}
</script>
</body></html>
STRING OBJECTS
A JavaScript string simply stores a series of characters like "John Doe".
A string can be any text inside quotes. You can use single or double quotes:
var answer = "It's alright";
var answer = "He is called 'Johnny'";
var answer = 'He is called "Johnny"';
String Length
The length of a string is found in the built in property length:
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;
Special Characters
Because strings must be written within quotes, JavaScript will misunderstand
this string:
var y = "We are the so-called "Vikings" from the north."
The string will be chopped to "We are the so-called ".
The solution to avoid this problem, is to use the \ escape character.
The backslash escape character turns special characters into string characters:
var x = 'It\'s alright';
var y = "We are the so-called \"Vikings\" from the north."
22UAD502 FULL STACK DEVELOPMENT UNIT II
The escape character (\) can also be used to insert other special characters in a
string.
This is the list of special characters that can be added to a text string with the
backslash sign:
Code Outputs
REGULAR EXPRESSIONS
• A regular expression is a sequence of characters that forms a search pattern.
• When you search for data in a text, you can use this search pattern to describe
what you are searching for.
• A regular expression can be a single character, or a more complicated pattern.
• Regular expressions can be used to perform all types of text search and text
replace operations.
Syntax
A regular expression could be defined with the RegExp () constructor, as
follows −
var pattern = /pattern/attibutes;
OR
var pattern = new RegExp(pattern, attributes);
Here is the description of the parameters –
• pattern − A string that specifies the pattern of the regular expression or another
regular expression.
• attributes − An optional string containing any of the "g", "i", and "m" attributes
that specify global, case-insensitive, and multiline matches, respectively.
Brackets
Brackets ([]) have a special meaning when used in the context of regular
expressions. They are used to find a range of characters.
Expression Description
[...] Any one character between the brackets.
[^...] Any one character not between the brackets.
[0-9] It matches any decimal digit from 0 through 9.
[a-z] It matches any character from lowercase a through lowercase z.
22UAD502 FULL STACK DEVELOPMENT UNIT II
Literal characters
Character Description
Alphanumeric Itself
\0 The NUL character (\u0000)
\t Tab (\u0009)
\n Newline (\u000A)
\v Vertical tab (\u000B)
\f Form feed (\u000C)
\r Carriage return (\u000D)
\xnn The Latin character specified by the hexadecimal number nn;
for example, \x0A is the same as \n
\d a digit (0-9)
\D a non-digit
\w a word character (a-z, A-Z, 0-9, _)
\W a non-word character
[\b] a literal backspace (special case).
[aeiou] matches a single character in the given set
[^aeiou] matches a single character outside the given set
(foo|bar|baz) matches any of the alternatives specified
Modifiers
Several modifiers are available that can simplify the way you work
with regexps, like case sensitivity, searching in multiple lines, etc.
Modifier Description
i Perform case-insensitive matching.
M Specifies that if the string has newline or carriage return characters, the
^ and $ operators will now match against a newline boundary, instead of
G Performs a global matchthat is, find all matches rather than stopping
after the first match.
<p id="demo"></p>
<script>
FunctionmyFunction() {
varstr = "Velammal Institute of Technology";
var n = str.search(/Institute/i);
document.getElementById("demo").innerHTML = n;
}
</script>
</body></html>
With the 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
22UAD502 FULL STACK DEVELOPMENT UNIT II
Example
The following example changes the content (the innerHTML) of the <p>
element with id="demo":
<html>
<body>
<p id="demo"></p>
22UAD502 FULL STACK DEVELOPMENT UNIT II
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>
</body>
</html>
In the example above, getElementById is a method, while innerHTML is
a property.
The getElementById Method
The most common way to access an HTML element is to use the id of the
element.
In the example above the getElementById method used id="demo" to find the
element.
The innerHTML Property
The easiest way to get the content of an element is by using
the innerHTML property.
The innerHTML property is useful for getting or replacing the content of HTML
elements.
The HTML DOM Document
In the HTML DOM object model, the document object represents your web
page.
The document object is the owner of all other objects in your web page.
If you want to access objects in an HTML page, you always start with accessing
the document object.
Below are some examples of how you can use the document object to access and
manipulate HTML.
Finding HTML Elements
Method Description
document.getElementById() Find an element by element id
document.getElementsByTagName() Find elements by tag name
document.getElementsByClassName() Find elements by class name
Changing HTML Elements
Method Description
</body>
</html>
In this example, a function is called from the event handler:
<!DOCTYPE html>
<html>
<body>
<script>
function changeText(id) {
id.innerHTML = "Ooops!";
22UAD502 FULL STACK DEVELOPMENT UNIT II
}
</script>
</body>
</html>
Assign Events Using the HTML DOM
The HTML DOM allows you to assign events to HTML elements using
JavaScript:
Assign an onclick event to a button element:
<script>
document.getElementById("myBtn").onclick = displayDate;
</script>
In the example above, a function named displayDate is assigned to an HTML
element with the id="myBtn".
The function will be executed when the button is clicked.
The onload and onunload Events
The onload and onunload events are triggered when the user enters or leaves the
page.
The onload event can be used to check the visitor's browser type and browser
version, and load the proper version of the web page based on the information.
The onload and onunload events can be used to deal with cookies.
<body onload="checkCookies()">
The onchange Event
The onchangeevent are often used in combination with validation of input fields.
Below is an example of how to use the onchange. The upperCase() function will
be called when a user changes the content of an input field.
<input type="text" id="fname" onchange="upperCase()">
<!DOCTYPE html>
<html>
<head>
<script>
FunctionmyFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>
</head>
<body>
22UAD502 FULL STACK DEVELOPMENT UNIT II
</body>
</html>
The onmouseover and onmouseout Events
The onmouseover and onmouseout events can be used to trigger a function when
the user mouses over, or out of, an HTML element.
<!DOCTYPE html>
<html>
<body>
<div onmouseover="mOver(this)" onmouseout="mOut(this)"
style="background-color:#D94A38;width:120px;height:20px;padding:40px;">
Mouse Over Me</div>
<script>
FunctionmOver(obj) {
obj.innerHTML = "Thank You"
}
FunctionmOut(obj) {
obj.innerHTML = "Mouse Over Me"
}
</script>
</body></html>
The onmousedown, onmouseup and onclick Events
The onmousedown, onmouseup, and onclick events are all parts of a mouse- click.
First when a mouse-button is clicked, the onmousedown event is triggered, then,
when the mouse-button is released, the onmouseup event is triggered, finally,
when the mouse-click is completed, the onclick event is triggered.
<!DOCTYPE html>
<html>
<body>
FunctionmUp(obj) {
obj.style.backgroundColor="#D94A38";
obj.innerHTML="Thank You";
}
</script>
</body>
</html>
The onfocus()
Change the background-color of an input field when it gets focus.
<!DOCTYPE html>
<html>
<head>
<script>
FunctionmyFunction(x) {
x.style.background = "yellow";
}
</script>
</head>
<body>
Enter your name: <input type="text" onfocus="myFunction(this)">
<p>When the input field gets focus, a function is triggered which changes the
background-color.</p>
</body>
</html>
Create a web page using two image files, which switch between one another
as the mouse pointer moves over the images. Use the on Mouse Over and on
Mouse Out
<!DOCTYPE html>
<html>
<head>
<script>
Functionlighton() {
document.getElementById('myimage').src = "bulbon.gif";
}
Functionlightoff() {
document.getElementById('myimage').src = "bulboff.gif";
22UAD502 FULL STACK DEVELOPMENT UNIT II
}
</script>
</head>
<body>
</body>
</html>
EXCEPTION HANDLING
There are three types of errors in programming: (a) Syntax Errors, (b) Runtime
Errors, and (c) Logical Errors.
Syntax Errors
Syntax errors, also called parsing errors, occur at compile time in traditional
programming languages and at interpret time in JavaScript.
Runtime Errors
Runtime errors, also called exceptions, occur during execution (after
compilation/interpretation).
Logical Errors
Logic errors can be the most difficult type of errors to track down. These errors
are not the result of a syntax or runtime error. Instead, they occur when you make
a mistake in the logic that drives your script and you do not get the result you
expected.
The try...catch...finally Statement
The try statement lets you test a block of code for errors.
The catch statement lets you handle the error.
The throw statement lets you create custom errors.
The finally statement lets you execute code, after try and catch, regardless of the
result.
JavaScript implements the try...catch...finally construct as well as
the throw operator to handle exceptions.
You can catch programmer-generated and runtime exceptions, but you
cannot catchJavaScript syntax errors.
Here is the try...catch...finally block syntax −
<scripttype="text/javascript">
22UAD502 FULL STACK DEVELOPMENT UNIT II
<!--
try{
// Code to run
[break;]
}
catch( e ){
// Code to run if an exception occurs
[break;]
}
[ finally{
// Code that is always executed regardless of
// an exception occurring
}]
//-->
</script>
The try block must be followed by either exactly one catch block or
one finally block (or one of both). When an exception occurs in the try block, the
exception is placed in e and the catch block is executed. The optional
finally block executes unconditionally after try/catch.
<!DOCTYPE html>
<html>
<body>
<p id="message"></p>
<script>
FunctionmyFunction() {
var message, x;
message = document.getElementById("message");
message.innerHTML = "";
x = document.getElementById("demo").value;
try {
if(x == "") throw "is empty";
if(isNaN(x)) throw "is not a number";
x = Number(x);
22UAD502 FULL STACK DEVELOPMENT UNIT II