Unit Ii Notes
Unit Ii Notes
Unit Ii Notes
Application of JavaScript
o Client-side validation,
o Dynamic drop-down menus,
o Displaying date and time,
o Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog
box and prompt dialog box),
o Displaying clocks etc.
Example
<body>
<h2>Welcome to JavaScript</h2>
<script>
</script>
</body>
</html>
<html>
<body>
<script type="text/javascript">
alert("Hello Javatpoint");
</script>
</body>
</html>
<html>
<script type="text/javascript">
function msg(){
alert("Hello Javatpoint");
</script>
</head>
<body>
<p>Welcome to Javascript</p>
<form>
</form>
</body>
</html>
External javascript
Message.js
function msg(){
alert("Hello Javatpoint");
}
HTML File
<html>
<head>
JavaScript provides different data types to hold different types of values. There are two types
of data types in JavaScript.
JavaScript is a dynamic type language, means you don't need to specify type of the variable
because it is dynamically used by JavaScript engine. You need to use var here to specify the
data type. It can hold any type of values such as numbers, strings etc. For example:
There are five types of primitive data types in JavaScript. They are as follows:
JavaScript Comment
The JavaScript comments are meaningful way to deliver message. It is used to add
information about the code, warnings or suggestions so that end user can easily
interpret the code.
Types of Comments
1. Single-line Comment
2. Multi-line Comment
It is represented by double forward slashes (//). It can be used before and after the
statement.
Example:
<html>
<body>
<script>
document.write("hello javascript");
</script>
</body>
</html>
It can be used to add single as well as multi line comments. So, it is more convenient.
Example:
<html>
<body>
<script>
</script>
</body>
</html>
JavaScript Variable
A JavaScript variable is simply a name of storage location. There are two types of
variables in JavaScript: local variable and global variable.
There are some rules while declaring a JavaScript variable (also known as identifiers).
var x = 10;
var _value="sonoo";
var 123=30;
var *aa=320;
Example Program
<html>
6 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE
<body>
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
</body>
</html>
<script>
function abc(){
var x=10;//local variable
}
</script>
Or,
<script>
if(10<13){
var y=20;//JavaScript local variable
}
</script>
<script>
var data=200;//gloabal variable
function a(){
7 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE
document.writeln(data);
}
function b(){
document.writeln(data);
}
a();//calling JavaScript function
b();
</script>
Java Script Output
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
Using document.write()
Using window.alert()
<!DOCTYPE html>
<html>
<body>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
Using console.log()
For debugging purposes, you can call the console.log() method in the browser to
display data.
Using console.log () Output
<!DOCTYPE html>
<html>
<body>
<script>
console.log(5 + 6);
</script>
</body>
</html>
Prompt Box
A prompt box is often used if you want the user to input a value before entering a page.
Syntax
window.prompt("sometext","defaultText");
1 <?xml version = "1.0"?>
2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
4
Arithmetic operators are used to perform arithmetic operations on the operands. The
following operators are known as JavaScript arithmetic operators.
+ Addition 10+20 = 30
- Subtraction 20-10 = 10
/ Division 20/10 = 2
The JavaScript comparison operator compares the two operands. The comparison operators
are as follows:
The bitwise operators perform bitwise operations on operands. The bitwise operators are as
follows:
= Assign 10+10 = 20
Operator Description
(?:) Conditional Operator returns value based on the condition. It is like if-
else.
The JavaScript if-else statement is used to execute the code whether condition is true or
false. There are three forms of if statement in JavaScript.
JavaScript If statement
It evaluates the content only if expression is true. The signature of JavaScript if statement is
given below.
if(expression){
//content to be evaluated
}
Example Output
<html>
<script>
function age()
{
if(document.getElementById("t1").value>=18)
{
window.alert("ELIGIBLE FOR VOTE")
}
}
</script>
<body>
<h1>Enter the age:<input
type="text"id="t1"><br></h1>
<button
type="button"onclick="age()">VERIFY</button>
</body>
</html>
if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}
It evaluates the content only if expression is true from several expressions. The signature of
JavaScript if else if statement is given below.
if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
}
else{
//content to be evaluated if no expression is true
}
Example Output
<html> a is equal to 20
<body>
<script>
var a=20;
if(a==10){
document.write("a is equal to 10");
16 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>
</body>
</html>
JavaScript Switch
The JavaScript switch statement is used to execute one code from multiple expressions.
switch(expression){
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
......
default:
code to be executed if above values are not matched;
}
Example Output
<!DOCTYPE html> B Grade
<html>
<body>
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
The JavaScript loops are used to iterate the piece of code using for, while, do while or for-in
loops. It makes the code compact. It is mostly used in array.
1. for loop
2. while loop
3. do-while loop
4. for-in loop
The JavaScript for loop iterates the elements for the fixed number of times. It should be used
if number of iteration is known. The syntax of for loop is given below.
while (condition)
{
code to be executed
}
Example Output
<!DOCTYPE html> 11
<html> 12
<body>
<script>
13
var i=11; 14
while (i<=15) 15
{
document.write(i + "<br/>");
i++;
}
</script>
</body>
</html>
The JavaScript do while loop iterates the elements for the infinite number of times like
while loop. But, code is executed at least once whether condition is true or false. The syntax
of do while loop is given below.
do{
code to be executed
}while (condition);
Example Output
<!DOCTYPE html> 21
<html> 22
<body>
<script>
23
var i=21; 24
do{ 25
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>
</body>
19 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE
</html>
JavaScript functions are used to perform operations. We can call JavaScript function many
times to reuse the code.
Program Output
<html>
<body>
<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
</body>
</html>
Program Output
<html>
<body>
<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
</body>
</html>
Function with Return Value
Program Output
1. <script> hello javatpoint! How r u?
2. function getInfo(){
3. return "hello javatpoint! How r u?";
21 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE
4. }
5. </script>
6. <script>
7. document.write(getInfo());
8. </script>
JavaScript Array
JavaScript array is an object that represents a collection of similar type of elements.
There are 3 ways to construct array in JavaScript
o By array literal
o By creating instance of Array directly (using new keyword)
o By using an Array constructor (using new keyword)
1) JavaScript array literal:
Syntax: var arrayname=[value1,value2.....valueN];
Program Output
<html>
<body>
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
</body>
</html>
Program Output
<html> Jai
<body> Vijay
<script> Smith
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
</body>
</html>
"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."
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).
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>
</body>
</html>
The getElementById Method
The most common way to access an HTML element is to use the id of the element.
The easiest way to get the content of an element is by using the innerHTML property.
Method Description
Property Description
Method Description
The easiest way to modify the content of an HTML element is by using the innerHTML property.
To change the content of an HTML element, use this syntax:
<script>
document.getElementById("p1").innerHTML = "New text!";
</script>
</body>
<button type="button"
onclick="document.getElementById('id1').style.color = 'red'">
Click Me!</button>
</body>
</html>
var element=document.getElementById("div1");
element.appendChild(para);
</script>
Parameter Description
newnode Required.
The node to insert.
oldnode Required.
The node to remove.
Types of Errors
While coding, there can be three types of errors in the code:
1. Syntax Error: When a user makes a mistake in the pre-defined syntax of a programming
language, a syntax error may appear.
2. Runtime Error: When an error occurs during the execution of the program, such an error is
known as Runtime error. The codes which create runtime errors are known as Exceptions.
Thus, exception handlers are used for handling runtime errors.
3. Logical Error: An error which occurs when there is any logical mistake in the program that
may not produce the desired output, and may terminate abnormally. Such an error is known as
Logical error.
Types of Errors
1. RangeError: It creates an instance for the error that occurs when a numeric variable
or parameter is out of its valid range.
2. ReferenceError: It creates an instance for the error that occurs when an invalid
reference is de-referenced.
3. TypeError: When a variable is not a valid type, an instance is created for such an
error.
4. InternalError: It creates an instance when the js engine throws an internal error.
o throw statements
o try…catch statements
o try…catch…finally statements.
The try statement allows you to define a block of code to be tested for
errors while it is being executed.
The catch statement allows you to define a block of code to be executed,
if an error occurs in the try block.
Throw Statement
Throw statements are used for throwing user-defined errors.
User can define and throw their own custom errors.
When throw statement is executed, the statements present after it will not execute.
The control will directly pass to the catch block.
Syntax:
throw exception;
try…catch…throw syntax
try{
throw exception; // user can define their own exception
}
catch(error){
expression; } // code for handling exception.
Example program for user-defined throw statement Output
<html> Exception Handling This is
<head>Exception Handling</head> the throw keyword
<body>
<script>
29 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE
try {
throw new Error('This is the throw keyword'); //user-defined throw
statement.
}
catch (e) {
document.write(e.message); // This will generate an error message
}
</script>
</body>
</html>
try…catch…finally statements
finally is an optional block of statements which is executed after the execution of try
and catch statements.
Syntax
try {
Try Block to check for errors.
}
catch(err) {
Catch Block to display errors.
}
finally {
Finally Block executes regardless of the try / catch result.
}
Program for finally Output
<html> Exception Handling ok Value of a is 2
<head>Exception Handling</head>
<body>
<script>
try{
var a=2;
if(a==2)
document.write("ok");
}
catch(Error){
document.write("Error found"+e.message);
}
finally{
document.write("Value of a is 2 ");
}
</script>
</body>
30 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE
</html>
Form validation occurs at the server, after the client had entered all necessary data
and then pressed the Submit button. If some of the data that had been entered by the
client had been in the wrong form or was simply missing, the server would have to send
all the data back to the client and request that the form be resubmitted with correct
information. This is a lengthy process and over burdening server. JavaScript, provides a
way to validate form's data on the client's computer before sending it to the web server.
Form validation generally performs two functions:
Basic Validation - Checking the form to make sure that the data entered is
right.
Data Format Validation – Checking the data entered in the form for right
value.
Program for Form Validation
<html><head>
<title>Form Validation</title>
<script type="text/javascript">
</script></head><body>
<form action="/cgi-bin/test.cgi" name="myForm" onsubmit="return(validate());">
<table cellspacing="2" cellpadding="2" border="1">
<tr><td align="right">Name</td>
<td><input type="text" name="Name" /></td></tr>
<tr><td align="right">EMail</td>
<td><input type="text" name="EMail" /></td></tr>
<tr><td align="right">Zip Code</td>
<td><input type="text" name="Zip" /></td></tr>
<tr><td align="right">Country</td><td>
<select name="Country">
<option value="-1" selected>[choose yours]</option>
<option value="1">USA</option>
<option value="2">UK</option>
<option value="3">INDIA</option>
31 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE
</select></td></tr>
<tr><td align="right"></td>
<td><input type="submit" value="Submit" /></td>
</tr></table></form>
<script type="text/javascript"> function validate()
{
if( document.myForm.Name.value == "" )
{
alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.EMail.value == "" )
{
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ;
return false;
}
if( document.myForm.Zip.value == "" ||isNaN( document.myForm.Zip.value ) ||
document.myForm.Zip.value.length != 5 )
{
alert( "Please provide a zip in the format #####." );
document.myForm.Zip.focus() ;
return false;
}
if( document.myForm.Country.value == "-1" )
{
alert( "Please provide your country!" );
return false;
}
return( true );
32 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE
}
</script>
</body>
Property Description
Method Description
index Required.
The position to add/remove items.
Negative value defines the position from the end of the array.
howmany Optional.
Number of items to be removed.
<p id="demo"></p>
<script>
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;
</script>
</body>
</html>
Method Description
Math Object
<script>
document.writeln(Math.ceil(7.2)+"<br>");
document.writeln(Math.ceil(0.2));
</script>
</body>
</html>
mouseover onmouseover When the cursor of the mouse comes over the
element
mousedown onmousedown When the mouse button is pressed over the element
mouseup onmouseup When the mouse button is released over the element
Keyboard events:
Keydown & onkeydown & When the user press and then release the key
Keyup onkeyup
Form events:
load onload When the browser finishes the loading of the page
unload onunload When the visitor leaves the current webpage, the
browser unloads it
resize onresize When the visitor resizes the window of the browser
Click Event
Program Output
<html>
<head> Javascript Events </head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function clickevent()
{
document.write("This is ACET");
}
//-->
</script>
<form>
<input type="button" onclick="clickevent()" value="Who's
this?"/>
</form>
</body>
</html>
MouseOver Event
Program Output
<html>
<head>
<h1> Javascript Events </h1>
</head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
Focus Event
Program Output
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onfocus="focusevent()"/>
<script>
<!--
function focusevent()
{
document.getElementById("input1").style.background="
aqua";
}
//-->
</script>
</body>
</html>
Keydown Event
Program Output
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onkeydown="keydownevent()"/>
<script>
<!--
function keydownevent()
{
document.getElementById("input1");
alert("Pressed a key");
}
//-->
Load Event
Program Output
<html>
<head>Javascript Events</head>
</br>
<body onload="window.alert('Page successfully loaded');">
<script>
<!--
document.write("The page is loaded successfully");
//-->
</script>
</body>
</html>
Introduction to DHTML
DHTML stands for Dynamic Hypertext Markup language i.e., Dynamic HTML.
Components of Dynamic HTML
o HTML 4.0
o CSS
o JavaScript
o DOM.
HTML 4.0
o HTML is a client-side markup language, which is a core component of the
DHTML. It defines the structure of a web page with various defined basic
elements or tags.
CSS
o CSS stands for Cascading Style Sheet, which allows the web users
or developers for controlling the style and layout of the HTML
elements on the web pages.
JavaScript
o JavaScript is a scripting language which is done on a client-side.
o DHTML uses the JavaScript technology for accessing, controlling,
and manipulating the HTML elements.
DOM
o DOM is the document object model. It is a w3c standard, which is a
standard interface of programming for HTML.
42 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE
Difference between HTML and DHTML
HTML DHTML
It is used for developing and It is used for creating and designing
creating web pages. the animated and interactive web
sites or pages.
This markup language creates This concept creates dynamic
static web pages. web pages.
A simple page which is created A page which is created by a
by a user without using the user using the HTML, CSS,
scripts or styles called as an DOM, and JavaScript
HTML page. technologies called a DHTML
page.
HTML is simply a markup DHTML is not a language, but it
language. is a set of technologies of web
development.
DHTML Tasks
Following are some of the tasks that can be performed with JavaScript:
• Performing html tasks
• Performing CSS tasks
• Handling events
• Validating inputs
Performing HTML Tasks:
DHTML Code performing HTML tasks Output
<html>
<head>
<title>DOM programming</title>
</head>
<body>
<h1>GeeksforGeeks</h1>
<p id = "geeks">Hello Geeks!</p>
<script style = "text/javascript">
document.getElementById("geeks").innerHTML ="A
computer science portal for geeks";
</script>
</body>
</html>
Performing CSS Tasks:
DHTML CSS for changing the style of the HTML element
DHTML Events
• An event is defined as changing the occurrence of an object.
• It is compulsory to add the events in the DHTML page. Without events, there will be
no dynamic content on the HTML page. The event is a term in the HTML, which
triggers the actions in the web browsers.
• Example of events:
• Click a button.
• Submitting a form.
• An image loading or a web page loading, etc.
DHTML Code performing HTML tasks Output
<html>
<head>
<title>
Example of onclick event
</title>
<script type="text/javascript">
function ChangeText(ctext)
{
ctext.innerHTML=" Hi Akshaya!!!";
}
</script>
</head>
<body>
<font color="red"> Click on the Given text for changing it: <br>
</font>
<font color="blue">
44 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE
<h1 onclick="ChangeText(this)"> Hello World! </h1>
</font>
</body>
</html>
h1 {
color: green;
}
</style>
<h1>
GeeksforGeeks
</h1>
<h4>
DHTML JavaScript
</h4>
<p>
Enter graduation percentage:
</p>
<input id="perc">
<button type="button" onclick="Validate()">
Submit
</button>
<p id="demo"></p>
<script>
function Validate() {
var x,text;
x=document.getElementById("perc").value;
if(isNaN(x)||x<60) {
window.alert("Not selected in GeeksforGeeks");
} else {
document.getElementById("demo").innerHTML=
"Selected: Welcome to GeeksforGeeks";
document.getElementById("demo").style.color="#009900";
}
}
45 UNIT II PREPARED BY : Mr.V.Balamurugan, AP (Sr. G.)/CSE
</script>
JSON Introduction
JSON is a text-based data exchange format derived from JavaScript that is used in
web services and other connected applications.
JSON defines only two data structures
Objects and Arrays
An object is a set of name-value pairs
Array is a list of values
JSON defines seven value types: string, number, object, array, true, false and null.
Objects are enclosed in braces ({})
Array are enclosed in brackets ([])
JSON Syntax
<body>
<p id="para"></p>
<script>
var jsonObjectArray = {
var x = jsonObjectArray.books[0];
document.getElementById("para").innerHTML= x.name + " by " + x.author;
</script>
</body>
</html>
Output:
Let Us C by Yashavant Kanetkar
JSON Function files:
Using JSON, it is possible to define a function in a separate external JS file and we
can access this functionality from HTML document.
Example code
myFile.js
student({
{“name”: “AAA”, “roll_no”: “10”, “city”: “Pune”},
{“name”: “BBB”, “roll_no”: “20”, “city”: “Mumbai”},
{“name”: “CCC”, “roll_no”: “30”, “city”: “Kolkata”},
{“name”: “DDD”, “roll_no”: “40”, “city”: “Chennai”},
JSON_File_Demo.html
<!DOCTYPE html>
<html>
<body>
<div id="myID"></div>
<script>
Output
Roll_No Name City
10 AAA Pune
20 BBB Mumbai
30 CCC Kolkata
40 DDD Chennai