Professional Documents
Culture Documents
in
Unit – III
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);
Example :
var stringArray = new Array();
stringArray[0] = "one";
stringArray[1] = "two";
stringArray[2] = "three";
stringArray[3] = "four";
<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>
• 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
the argument. Changing the argument inside the function doesn’t affect the variable
passed from outside the function.
<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>
<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>
• 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>
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>
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";
}
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
<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
<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
<!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
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
<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
<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
objectName.methodname()
Example: Math.methodname(number)
Math.propertyname
20
21
22
<html>
<head>
<title>Math Object Properties</title>
</head>
<body>
<script>
document.write("Euler's number is "+Math.E);
document.write("<br> π value is "+Math.PI);
document.write("<br> SQRT value of 2 is "+Math.SQRT2);
document.write("<br> SQRT value of 1/2 is "+Math.SQRT1_2);
document.write("<br> natural logarithm of 2 is "+Math.LN2);
document.write("<br> natural logarithm of 10 is "+Math.LN10);
document.write("<br> Base 2 Logarithm E Value is "+Math.LOG2E);
document.write("<br> Base 10 Logarithm E Value is “+Math.LOG10E);
</script>
</body>
</html>
23
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
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
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
28
<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
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
<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
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
<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
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 object’s cookie property.
• A cookie has the syntax “identifier=value,” 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 the cookie. If a cookie’s expiration date is not set, then the cookie expires by default
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