Unit-2 2
Unit-2 2
Chapter-1 (Arrays)
1.1 Introduction :-
An array is a special type of variable, which can store multiple values
using special syntax. Every value is associated with numeric index starting with 0.
The following figure illustrates how an array stores values.
Note :- JavaScript array can store multiple element of different data types. It is not required
to store value of same data type in an array.
1.2.2 Array Constructor
We can initialize an array with Array constructor syntax using new keyword.
The Array constructor has following three forms.
Syntax:
var arrayName = new Array();
var arrayName = new Array(Number length);
var arrayName = new Array(element1, element2,... elementN);
1
Example :
var stringArray = new Array();
stringArray[0] = "one";
stringArray[1] = "two";
stringArray[2] = "three";
stringArray[3] = "four";
2
Example Program :- By creating instance of Array directly (using new keyword)
<html>
<head>
<title>Instance of Array directly</title>
</head>
<body>
<script>
var arr=new Array();
arr[0]="hello";
arr[1]="World";
arr[2]="10";
arr[3]="10.78";
for (var i=0;i<arr.length;i++)
{
document.write(arr[i] + "<br/>");
}
</script>
</body>
</html>
<html>
<head>
<title>By using an Array constructor</title>
</head>
<body>
<script>
var arr=new Array("hello","world",10,10.78);
for (var i=0;i<arr.length;i++)
{
document.write(arr[i] + "<br/>");
}
</script>
</body>
</html>
3
1.5 References and Reference Parameters
Two ways to pass arguments to functions (or methods) in many programming languages
are pass-by-value and pass-by-reference.
1.5.1 Pass by value
In pass by value, a function is called by directly passing the value of the variable as
<html>
<head>
<title>Pass by Value</title>
</head>
<body>
<script>
var a = 1;
var b = 2;
document.write("Before Swapping");
document.write("<br>a="+a + "<br>"+"b="+b);
function Passbyvalue(a, b)
{
var temp;
temp = a;
a = b;
b = temp;
document.write("<br>After Swapping");
document.write("<br>a="+a + "<br>"+"b="+b);
}
Passbyvalue(a, b);
document.write("<br>After Function calling");
document.write("<br>a="+a + "<br>"+"b="+b);
</script>
</body>
</html>
4
1.5.2 Pass by reference
In Pass by Reference, Function is called by directly passing the reference/address
of the variable as an argument. So changing the value inside the function also change the
original value.
<html>
<head>
<title>Pass by Reference</title>
</head>
<body>
<script>
var obj={
a:1,b:2
}
document.write("Before Swapping");
document.write("<br>a="+obj.a + "<br>"+"b="+obj.b);
function PassbyReference(obj)
{
var temp;
temp = obj.a;
obj.a = obj.b;
obj.b = temp;
document.write("<br>After Swapping");
document.write("<br>a="+obj.a + "<br>"+"b="+obj.b);
}
PassbyReference(obj);
document.write("<br>After Function Calling");
document.write("<br>a="+obj.a + "<br>"+"b="+obj.b);
</script>
</body>
</html>
5
1.6 Passing Arrays to Functions
To pass an array argument to a function, specify the name of the array (a reference to the
array) without brackets.
<html>
<head>
<title>Pass Array to a Function</title>
</head>
<body>
<script>
var Subjects = ["Maths","Computers","English"];
function displayName(arr)
{
for(var i=0; i<arr.length; i++)
{
document.write("<br>"+arr[i]);
}
}
displayName(Subjects);
</script>
</body>
</html>
JavaScript does not provide the multidimensional array natively. However, you can create
a multidimensional array by defining an array of elements, where each element is also
another array.
A multidimensional array is an array that contains another array.
Example 1:
<html>
<head>
<title>Multidimensional Arrays</title>
</head>
<body>
<script>
var studentsData = [['Maths',65],['Cs',75],['English',80]];
for (var i=0;i<studentsData.length;i++)
{
document.write(studentsData[i]+"<br>");
}
</script>
</body>
</html>
6
Example 2:
<html>
<head>
<title>Multidimensional Arrays</title>
</head>
<body>
<script>
var student1 = ['Naresh', 24];
var student2 = ['Radha', 23];
var student3 = ['Rajini', 24];
var studentsData = [student1, student2, student3];
for (var i=0;i<studentsData.length;i++)
{
document.writeln(studentsData[i]+"<br>");
}
</script>
</body>
</html>
7
Chapter-2 (Events)
2.1 Registering event Handling
Functions that handle events are called event handlers. event handler which is a
piece of code that will execute to respond to that event
An event handler is also known as an event listener. It listens to the event and
responds accordingly to the event fires.
There are two types of events that can be used to trigger scripts:
Window events, which occur when something happens to a window. For example,
a page loads or unloads or focus is being moved to or away from a window or frame .
User events, which occur when the user interacts with elements in the page using
a mouse (or other pointing device) or a keyboard, such as placing the mouse over an
element, clicking on an element, or moving the mouse off an element.
2.2 event onload
The onload event occurs when the document has been completely loaded, including
dependent resources like JavaScript files, CSS files, and images.
<html>
<head>
<title>JS onload Event Demo</title>
</head>
<body onload=document.write('Loaded!')>
</body>
</html>
<html>
<head>
<title>mouse events</title>
<script>
function newimage()
{
document.img1.src="D:\html Logo.jpg";
}
8
function oldimage()
{
document.img1.src="D:\Css Logo.png";
}
</script>
</head>
<body>
<img name="img1" src="D:\Mouse.png" height="200" width="200"
onmouseover="newimage()" onmouseout="oldimage()">
</body>
</html>
onmouseover Output
onmouseout Output
9
<html>
<head>
<title>onfocus and onblur</title>
<script>
function highlightcolor(x)
{
x.style.background="yellow";
}
function regular(x)
{
x.style.background="white";
}
</script>
</head>
<body>
Enter your name:
<input type="text" onfocus="highlightcolor(this)"
onblur="regular(this)"> <br>
Enter your phone number:
<input type="text" onfocus="highlightcolor(this)"
onblur="regular(this)">
</body>
</html>
10
2.5 onsubmit and onreset
The onsubmit event is an event that occurs when you try to submit a form.
The onreset event occurs when the reset button in a form is clicked.
<html>
<head>
<title>onsubmit and onblur</title>
<script>
function resetfun()
{
alert("The form was reset");
}
function submitfun()
{
alert("The form was submitted");
}
</script>
</head>
<body>
<form action="" onsubmit="submitfun()" onreset="resetfun()">
Firstname: <input type="text" name="fname"><br>
Lastname: <input type="text" name="lname"><br>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
</body>
</html>
11
2.5 Event Bubbling
Event bubbling is a method of event propagation in the HTML DOM API when an event is
in an element inside another element, and both elements have registered a handle to that
event. It is a process that starts with the element that triggered the event and then bubbles
up to the containing elements in the hierarchy.
In event bubbling, the event is first captured and handled by the innermost element and
then propagated to outer elements.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Event Bubbling Demo</title>
<style type="text/css">
div, p, a
{
padding: 15px 30px;
display: block;
border: 2px solid #000;
}
</style>
</head>
<body>
<div onclick="alert('Bubbling: ' + this.tagName)"> DIV
<p onclick="alert('Bubbling: ' + this.tagName)"> P
<a href="#" onclick="alert('Bubbling: ' + this.tagName)">A</a>
</p>
</div>
</body>
</html>
12
13
2.6 More events
A list of some events supported by both Firefox and Internet Explorer is given with
Descriptions.
Event Purpose
Document has finished loading (if used in a frameset, all frames have
onload
finished loading).
onunload Document is unloaded, or removed, from a window or frameset.
Button on mouse (or other pointing device) has been clicked over the
onclick
element.
Button on mouse (or other pointing device) has been double - clicked
ondblclick
over the element.
Button on mouse (or other pointing device) has been depressed (but
onmousedown
not released) over the element.
Button on mouse (or other pointing device) has been released over
onmouseup
the element.
Cursor on mouse (or other pointing device) has been moved onto the
onmouseover
element.
Cursor on mouse (or other pointing device) has been moved while
onmousemove
over the element.
Cursor on mouse (or other pointing device) has been moved off the
onmouseout
element.
Event Purpose
onkeypress A key is pressed and released.
onkeydown A key is held down.
onkeyup A key is released.
onfocus Element receives focus either by mouse (or other pointing device)
onblur Element loses focus.
onsubmit A form is submitted
onreset A form is reset.
onselect User selects some text in a text field.
onchange A control loses input focus and its value has been changed since
gaining focus.
14
Example program on functions and onclick event
<html>
<head>
<title>function</title>
<script>
function product()
{
var a=10;
var b=20;
document.write("Multiplication value is:"+a*b);
}
</script>
</head>
<body>
<form>
<input type="button" value="Product" onclick="product()">
</form>
</body>
</html>
15
onkeyup event
<html>
<head>
<title>onkeyup event</title>
</head>
<body>
<script>
function display()
{
alert("event activated when the user releases a key.");
}
</script>
<form>
Enter the text:
<input type="text" onkeyup= "display()">
</form>
</body>
</html>
16
onload event
<html>
<head>
<title> HTML onload event</title>
<script>
function display()
{
alert(" Onload event")
}
</script>
</head>
<body onload="display()">
<h2> Page Loaded successfully </h2>
</body>
</html>
17
onmouseup and onmousedown event
<html>
<head>
<title> onmousedown and up attribute</title>
</head>
<body>
<p onmousedown="mouseDown(this)" onmouseup="mouseUp(this)">
Click Here to check onmousedown Event.<br>
<script>
function mouseDown(obj)
{
obj.style.color = "red";
}
function mouseUp(obj)
{
obj.style.color = "blue";
}
</script>
</body>
</html>
18
onresize event
<html>
<head>
<title> onresize event</title>
<script>
function display()
{
alert ("You have changed the size of thewindow!");
}
</script>
</head>
<body onresize="display()">
<p>Try to resize the browser window</p >
</body>
</html>
19
Chapter-3 (JAVA SCRIPT OBJECTS)
3.1 Introduction to Object Technology
Objects are a natural way of thinking about the world and about scripts that manipulate
XHTML documents.
JavaScript uses objects to perform many tasks and therefore is referred to as an object-
based programming language.
A JavaScript object is an entity having state and behaviour (properties and method).
JavaScript is an object-based language. Everything is an object in JavaScript.
Object-oriented design (OOD) models communication between objects
OOD encapsulates attributes and operations (behaviours) into objects.
Objects have the property of information hiding
3.2 Built-in Objects
Methods that allow you to perform actions upon data, and properties that tell you
something about the data. Each object having special purpose properties and methods.
We are having six objects in JavaScript
1. Math Object
2. String Object
3. Date Object
4. Boolean and Number Object
5. Document Object
6. Window Object
3.2.1 Math Object
Math is a built-in object that provides properties and methods for mathematical constants
and functions to execute mathematical operations.
A common way to access the property or Method of an object is the dot property
accessor:
objectName.propertyName
objectName.methodname()
Example: Math.methodname(number)
Math.propertyname
20
21
Example Program on Math Objects methods:
<html>
<head>
<title>Math Object Methods</title>
</head>
<body>
<script>
document.write("Absolute value : "+ Math.abs(-6.7));
document.write("<br> Ceil value is "+ Math.ceil(4.4));
document.write("<br> floor value is "+ Math.floor(4.4));
document.write("<br> rounded value is "+ Math.round(4.7));
document.write("<br> Maximum value is " +
Math.max(10,-5,100,800,2,4));
document.write("<br> Minimum value is " +
Math.min(10,-5,100,800,2,4));
document.write("<br> cosine of a number "+ Math.cos(90));
document.write("<br> sine of a number "+ Math.sin(90));
document.write("<br> tangent of a number "+ Math.tan(90));
document.write("<br> power value is "+ Math.pow(7,2));
document.write("<br> random number b/w 0 and 1 : "
+ Math.random());
document.write("<br> square root of a given number " +
Math.sqrt(9));
</script>
</body>
</html>
22
The Math object defines several commonly used mathematical constants
<html>
<head>
<title>Math Object Properties</title>
</head>
<body>
<script>
document.write("Euler's number is "+Math.E);
23
3.2.2 String Object
The JavaScript String object is a global object that is used to store strings.
A string is a series of characters treated as a single unit.
A string may include letters, digits and various special characters, such as +, -, *, /, and $.
String literals or string constants (often called anonymous String objects) are written as a
sequence of characters in double quotation marks or single quotation marks.
String Properties
Property Description
String Methods
The following table lists the standard methods of the String object.
Method Description
charAt() Returns the character at the specified index.
24
Returns the index of the first occurrence of the specified
indexOf()
value in a string.
25
<html>
<head>
<title>String Objects</title>
</head>
<body>
<script>
var st="Avanthi Degree College";
document.write("Length of the String is : "+st.length);
document.write("<br> charcater index is : "+st.charAt(0));
document.write("<br> Ascii value of the index is : " +
st.charCodeAt(2));
document.write("<br> index of the character : " +
st.indexOf("e"));
document.write("<br> index of the character : " +
st.lastIndexOf("e"));
document.write("<br> lowercase : " + st.toLowerCase());
document.write("<br> uppercase : " + st.toUpperCase());
document.write("<br> font color: " + st.fontcolor('red'));
document.write("<br> font size: " + st.fontsize(20));
</script>
</body>
</html>
26
3.2.3 Date Object
Date object provides methods for date and timemanipulations.
Date and time local time zone or
based on World Coordinated Universal Time (abbreviated UTC)
formerly called Greenwich Mean Time (GMT).
Most methods of the Date object have a local time zone and a UTC version.
The following table lists the standard methods of the Date object.
Method Description
getDate() Returns the day of the month (from 1-31).
getTimezoneOffset() Returns the time difference between UTC time and local
time, in minutes.
27
getUTCMinutes() Returns the minutes, according to universal time (from
0-59).
28
setYear() Deprecated. Use the setFullYear() method instead.
<html>
<head>
<title>DateObject</title>
</head>
<body>
<script>
var dt=new Date();
document.write("Today's Date is <br>"+dt);
document.write("<br> Current Year is "+dt.getFullYear());
document.write("<br> Current Date is "+dt.getDate());
document.write("<br> Current Day is "+dt.getDay());
var mm=dt.getMonth()+1;
document.write("<br> Current Month is "+mm);
document.write("<br> Hour is "+dt.getHours());
document.write("<br> Minutes are "+dt.getMinutes());
document.write("<br> Seconds are "+dt.getSeconds());
document.write("<br> Current Date is "+dt.getDate());
29
dt.setDate(15);
document.write("<br> Modified Date is "+dt.getDate());
dt.setFullYear(2030);
document.write("<br> Modified Year is "+dt.getFullYear());
</script>
</body>
</html>
<html>
<head>
<title>JavaScript Boolean Object Example</title>
</head>
<body>
<script>
var obj1=new Boolean(0);
var obj2=new Boolean(8);
var obj3=new Boolean(1);
var obj4=new Boolean("");
30
var obj5=new Boolean("Avanthi");
var obj6=new Boolean('False');
var obj7=new Boolean(null);
var obj8=new Boolean(NaN);
The following table lists the standard properties of the Number object.
Property Description
<html>
<head>
<title>Number Objects in JS </title>
</head>
<body>
<script>
document.write(Number.EPSILON+"<br>");
document.write(Number.MAX_VALUE+"<br>");
document.write(Number.MAX_SAFE_INTEGER+"<br>");
document.write(Number.MIN_VALUE+"<br>");
document.write(Number.MIN_SAFE_INTEGER+"<br>");
document.write(Number.NaN+"<br>");
document.write(Number.NEGATIVE_INFINITY+"<br>");
document.write(Number.POSITIVE_INFINITY+"<br>");
</script>
</body>
</html>
32
3.2.5 document Object
JavaScript Document object is an object that provides access to all HTML elements of a
document. When an HTML document is loaded into a browser window, then it becomes a
document object.
The document object stores the elements of an HTML document, such as HTML, HEAD,
BODY, and other HTML tags as objects.
<html>
<head>
<title>Document Properties</title>
</head>
<body>
<p id="demo">It Will change</p>
<script>
document.write("Hello" +"<br>");
document.getElementById("demo").innerHTML ="Set by ID";
document.write(document.lastModified +"<br>")
document.write(document.documentMode +"<br>")
document.write(document.title +"<br>")
document.write(document.url +"<br>")
</script>
</body>
</html>
33
3.2.6 window Object
JavaScript Window is a global Interface (object type) which is used to control the browser
window lifecycle and perform various operations on it.
The window object has four properties related to the size of the window:
The innerWidth and innerHeight properties return the size of the page viewport
inside the browser window (not including the borders and toolbars).
The outerWidth and outerHeight properties return the size of the browser window
itself.
<html>
<head>
<title>Dimension of Window</title>
</head>
<body>
<script>
var h = window.outerHeight
var w = window.outerWidth
document.write("Height and width of the window are: "+h+" and "+w)
var innerh = window.innerHeight
var innerw = window.innerWidth
document.write("<br>InnerHeight and Innerwidth of the window are:"
+innerh+" and "+innerw)
</script>
</body>
</html>
34
<html>
<head>
<title>JS Window Method Examples</title>
</head>
<body>
<h3>Perform various operations on Window object</h3>
<button onclick="createWindow()">Open a Window</button>
<button onclick="closewin()">Close the Window</button>
<button onclick="showAlert()">Show Alert in Window</button>
<script>
var win;
function createWindow() // Open window
{
win = window.open("", "My Window", "width=500, height=200");
}
function showAlert()
{
if(win == undefined)
{
// show alret in main window
window.alert("First create the new window, then show alert in it ");
}
else
{
win.alert("This is an alert");
} }
35
// Close window
function closewin()
{
win.close();
}
</script>
</body>
</html>
36
Example Program on alert method:
<html>
<head>
<title>Alert popup</title>
<script>
window.alert("Welcome to JavaScript Programming");
</script>
</head>
</html>
<html>
<head>
<title>prompt popup</title>
<script>
var res=window.prompt("enter user name");
window.alert("User name is "+res);
</script>
</head>
</html>
37
Example Program on confirm method:
<html>
<head>
<title>confirm popup</title>
<script>
var res=window.confirm("Do you want to Continue");
window.alert("User clicked on "+res);
</script>
</head>
</html>
3.2.7 cookie
A cookie is a small text file that lets you store a small amount of data (nearly 4KB) on the
user's computer.
Cookies are accessible in JavaScript through the document cookie property.
A cookie has the syntax where identifier is any valid JavaScript
variable identifier, and value is the value of the cookie variable.
When multiple cookies exist for one website, identifier-value pairs are separated by
semicolons in the document.cookie string.
The expires property in a cookie string sets an expiration date, after which the web browser
deletes
after the user closes the browser window
To create or store a new cookie, assign a name=value string to this property, like this:
document.cookie = "firstName=Santhosh";
<html>
<head>
<title>Using Cookies</title>
<script>
var now = new Date();
var hour = now.getHours();
38
var name;
if ( hour < 12 )
document.write( "Good Morning,")
else if (hour>12 && hour<16)
document.write("Good Afternoon,")
else
document.write("Good Evening,")
if(document.cookie)
{
var myCookie = unescape( document.cookie );
var cookieTokens = myCookie.split( "=" );
}
else
{
name=window.prompt("Please enter your name","Santhosh");
}
document.writeln(name + ", welcome to JavaScript programming!" );
</script>
</head>
</html>
Unit-III Questions
1. Define an array. Explain in brief about declaring and allocating
arrays
2. References and Reference Parameters (Pass by value or call by
value and Call by reference or pass by Reference)
3. Write a short note on passing arrays to functions
4. Write about Multidimensional arrays
5. Define event and event handler. What is meant by registering event
handler? Discuss the types of events
6. Explain different types of events (onload, onmouseover,
onmouseout, onfocus, onblur, onsubmit, onreset)
7. Explain about event bubbling
8. Built-in Objects (Date, Math, string, Boolean and Number ,
document and window)
9. Write a short note on cookies
39