[go: up one dir, main page]

0% found this document useful (0 votes)
14 views18 pages

WT Ass2

Timer functions in JavaScript allow executing code after a specified delay or at regular intervals. There are four main timer functions: setTimeout() executes code once after a delay, clearTimeout() cancels a setTimeout(), setInterval() executes code repeatedly at an interval, and clearInterval() cancels a setInterval(). Mouse and keyboard events trigger functions in response to user input like clicks, key presses, and pointer movement. Window and form events trigger functions in response to page/window loading, unloading, focusing, resizing and form element interactions.

Uploaded by

bhagyasree0409
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views18 pages

WT Ass2

Timer functions in JavaScript allow executing code after a specified delay or at regular intervals. There are four main timer functions: setTimeout() executes code once after a delay, clearTimeout() cancels a setTimeout(), setInterval() executes code repeatedly at an interval, and clearInterval() cancels a setInterval(). Mouse and keyboard events trigger functions in response to user input like clicks, key presses, and pointer movement. Window and form events trigger functions in response to page/window loading, unloading, focusing, resizing and form element interactions.

Uploaded by

bhagyasree0409
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

1. a. Explain briefly about Timer functions with examples?

In JavaScript the timer is a very important feature

• It allows us to execute a JavaScript function after a specified period, thereby making it possible to
add a new dimension, time, to our website.

• With the help of the timer, we can run a command at specified intervals, run loops repeatedly at a
predefined time, and synchronize multiple events in a particular time span.

• There are various methods for using it as in the following:

1. The setTimeout() method:


• Executes code at a specified interval.
• Syntax: setTimeout(function, delayTime)
• Here, function parameter specifies the method that the timer calls and the delayTime
parameter specifies the number of milliseconds to wait before calling the method.
2. The clearTimeout() method:
• Deactivates or cancels the timer that is set using the setTime() method.
• Syntax: clearTimeout(timer) • Here, timer is a variable that is created using the setTimeout()
method.
3. The setInterval() method:
• Executes a function after a specified time interval.
• Syntax: setInterval(function, intervalTime)
• Here, function parameters specify the method to be called; whereas, the intervalTime
parameter specifies the time interval between the function calls.
4. The clearInterval() method:
• Deactivates or cancels the timer that is set using the setInterval() method.
• Syntax: clearInterval(timer)
• The preceding syntax deactivates the inner timer variable that is created using the
setInterval() method.
Example: create a HTML document that demonstrate the calling function with timer in
JavaScript.
Example:
<!DOCTYPE html>
<html>
<head>
<title>Timer</title>
<script type="text/javascript">
var t,i;
function timedmsg(){
document.getElementById("msg").innerHTML="You have 5 sec to stop Timed messge";
t = setTimeout("alert('This is alert message')",5000);
}
function cleartimedmsg(){
clearTimeout(t);
}
function intervalmsg(){

1
document.getElementById("msg").innerHTML="You have 5 sec to stop Time Interval messge";
i = setInterval("alert('Interval message')",5000);
}
function clearintervalmsg(){
clearInterval(i);
}
</script>
</head>
<body>
<h1>Demonstrate calling function with timer</h1>
<h3><p id="msg"></p></h3>
<button onclick="timedmsg()">Set Timed Alert Box</button><br>
<button onclick="cleartimedmsg()">Clear Timed Alert Box</button><br>
<button onclick="intervalmsg()">Set Interval Alert Box</button><br>
<button onclick="clearintervalmsg()">Clear Interval Alert Box</button><br>
</body>
</html>

2. Explain briefly about mouse & keyboard events with


examples.
Keyboard Events:
Attribute Description New in HTML5
onkeydown Fires when a user is pressing a key No
onkeypress Fires when a user presses a key No
onkeyup Fires when a user releases a key No

Example:
<html>
<head>
<script>
function keyup()
{
document.write("This is a keyup event");
}
function keydown()
{
document.write("This is a keydown event");
}
function keypress()
{
document.write("This is a keypress event");
}
</script>
</head>
<body>

2
<input type="button" value="Keyevent" onkeyup="keyup()">
<input type="button" value="Keyevent" onkeydown="keydown()">
<input type="button" value="Keyevent" onkeypress="keypress()">
</body>
</html>

Mouse Events:
Attribute Description New in
HTML5
onclick Fires on a mouse click on the element No
ondblclick Fires on a mouse double-click on the element No
onmousedown Fires when a mouse button is pressed down on an element No
onmouseup Fires when a mouse button is released over an element No
onmouseover Fires when the mouse pointer moves over an element No
onmouseout Fires when the mouse pointer moves out of an element No
onmousemove Fires when the mouse pointer is moving while it is over an element No
onmousewheel Deprecated. Use the onwheel attribute instead Yes
onwheel Fires when the mouse wheel rolls up or down over an element Yes
ondrag Script to be run when an element is dragged Yes
ondragend Script to be run at the end of a drag operation Yes
ondragenter Script to be run when an element has been dragged to a valid drop target Yes
ondragleave Script to be run when an element leaves a valid drop target Yes
ondragover Script to be run when an element is being dragged over a valid drop target Yes
ondragstart Script to be run at the start of a drag operation Yes
ondrop Script to be run when dragged element is being dropped Yes
onscroll Script to be run when an element's scrollbar is being scrolled Yes

Example:
<html>
<head>
<script>
function mousemove()
{
document.write("This is a mouse move event");
}
function mouseclick()
{
document.write("This is a mouse click event");
}
function mouseup()
{
document.write("This is a mouse up event");
}
function mousedown()
{
document.write("This is a mouse down event");
}

3
function mousedblclick()
{
document.write("This is a mouse dblclick event");
}
function mouseout()
{
document.getElementById("myP").style.color = "blue";
}
function mouseover()
{
document.getElementById("myP").style.color = "red";
}
</script>
</head>
<body>
<p>Click the text below!</p>
<p id="myP" onmouseover="mouseOver()" onmouseout="mouseOut()">
The mouseOver() function sets the color of this text to red whenever mouse pointer moves
over an element. <br>
The mouseRelease() function sets the color of this text to blue whenever mouse pointer leaves
an element.
</p>
<input type="button" value="Keyevent" onmousemove="mousemove()">
<input type="button" value="Keyevent" onmouseup="mouseup()">
<input type="button" value="Keyevent" onmousedown="mousedown()">
<input type="button" value="Keyevent" onclick="mouseclick()">
<input type="button" value="Keyevent" ondblclick="mousedblclick()">
<input type="button" value="Keyevent" onmouseout="mouseout()">
<input type="button" value="Keyevent" onmouseover="mouseover()">
</body>

4
</html>

5
3. Explain briefly about window & form events with examples.

Attribute Description
onafterprint Script to be run after the document is printed
onbeforeprint Script to be run before the document is printed
onbeforeunload Script to be run when the document is about to be unloaded
onerror Script to be run when an error occurs
onhashchange Script to be run when there has been changes to the anchor part of the a URL
onload Fires after the page is finished loading
onmessage Script to be run when the message is triggered
onoffline Script to be run when the browser starts to work offline
ononline Script to be run when the browser starts to work online
onpagehide Script to be run when a user navigates away from a page
onpageshow Script to be run when a user navigates to a page
onpopstate Script to be run when the window's history changes
onresize Fires when the browser window is resized
onstorage Script to be run when a Web Storage area is updated
onunload Fires once a page has unloaded (or the browser window has been closed)
onundo Triggers at the time of performing the undo action in a document.
onblur Trigger when a window loses focus
onfocus Trigger when a window gets focus

Example:
<html>

<body onload="window.alert('Page successfully loaded');">

<h2>The focus Event</h2>

Enter your name: <input type="text" id="txt" onfocus="myFunction()">

<p>When the input field gets focus, a function changes the background-color.</p>

<img src="logo.jpg" onerror="display()">

<script>

6
function display()

alert("Image was unable to load");

function myFunction() {

document.getElementById("txt").style.background = "green";

document.write("The page is loaded successfully");

</script>

</body>

</html>

Form Events:
Events triggered by actions inside a HTML form (applies to almost all HTML elements, but is most
used in form elements):

Attribute Description

onfocus Fires the moment when the element gets focus


onblur Fires the moment that the element loses focus
onchange Fires the moment when the value of the element is changed
oninput Script to be run when an element gets user input
onselect Fires after some text has been selected in an element
oninvalid Script to be run when an element is invalid
Fires when the user writes something in a search field (for <input type="search"> )
onsearch

onreset Fires when the Reset button in a form is clicked


onsubmit Fires when a form is submitted

4. Explain in detail about Number, Math & Date objects with


examples?
. Number Object:
• All numbers in JavaScript are 64 bit(b bytes) floating point numbers and the range is
5e-324(negative) to 1.7976931348623157e+308(positive)
• Syntax: var num = new Number(value)
• Example: var n = new Number(’21.5768’); Properties:
Property Description

7
MIN_VALUE Returns the minimum numerical value possible in JavaScript
MAX_VALUE Returns the maximum numerical value possible in JavaScript
NEGATIVE_INFINITY Represents the value of negative infinity
POSITIVE_INFINITY Represents the value of infinity
Constructor Holds the value of constructor function that has created the object.
Prototype Adds property and methods to Number object

• Methods:
Property Description
toExponential(x) Converts a number into an exponential notation.
toFixed(x) Round up a number to x digits after the decimal
toPrecision(x) Round up a number to a length of x digits
toString(x) Returns a string value for the Number object
valueOf() Returns a primitive value for the Number type.

Example:
<html>

<body>

<h1>NUMBER OBJECT METHODS</h1>

<script>

var a=100;

var n=new Number(10);

p=Math.PI;

document.write("Type of a is : " + typeof a);

document.write("<br><br>After toString(), Type of n is : " + typeof n.toString());

document.write("<br><br>Exponential Function " + p.toExponential(5));

document.write("<br><br>Fixed Function " + p.toFixed(2));

document.write("<br><br>Precision Function " + p.toPrecision(4));

document.write("<br><br>isInteger Function " + Number.isInteger(p));

</script>

8
</body>

</html>

. Math Object:
• The math object is used to perform simple and complex
arithmetic operation.
• JavaScript math object is used to perform mathematical task.
Properties:
Description
Property
Holds approximate value
E Euler’s number 2.718
LN2 natural logarithmic of 2 0.693
LN10 natural logarithmic of 10 2.302
LOG2E base-2 logarithmic of E 1.442
LOG10E base-10 logarithmic of E 0.434
PI Number value of PI 3.142
SQRT1_2 Square root of 1/2 0.707
SQRT2 Square root of 2 1.414

• Methods
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

atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians
atan2(y, x) Returns the arctangent of the quotient of its arguments
ceil(x) Returns x, rounded upwards to the nearest integer
cos(x) Returns the cosine of x (x is in radians)
exp(x) Returns the value of Ex
floor(x) Returns x, rounded downwards to the nearest integer
log(x) Returns the natural logarithm of x
max(x1,x2,..xn) Returns the number with the highest value
min(x1,x2,..xn) Returns the number with the lowest value

9
pow(x, y) Returns the value of x to the power of y
random() Returns a random number between 0 and 1
round(x) Rounds x to the nearest integer
sin(x) Returns the sine of x (x is in radians)
sqrt(x) Returns the square root of x
tan(x) Returns the tangent of an angle

Example:
<html>

<body>

<h1>MATH OBJECT METHODS</h1>

<script>

var n=10.2;

var i=-10;

var j=0;

document.write("Round Function " + Math.round(n));

document.write("<br><br>Ceil Function " + Math.ceil(n));

document.write("<br><br>Floor Function " + Math.floor(n));

document.write("<br><br>Truncate Function " + Math.trunc(n));

document.write("<br><br>Sign Function +ve number " + Math.sign(n));

document.write("<br><br>Sign Function -ve number " + Math.sign(i));

document.write("<br><br>Sign Function null value " + Math.sign(j));

document.write("<br><br>Power Function " + Math.pow(4,2));

document.write("<br><br>Square Root Function " + Math.sqrt(16));

document.write("<br><br>Absolute Function " + Math.abs(i));

document.write("<br><br>Minimum Function " + Math.min(10,40,20,30,5));

document.write("<br><br>Maximum Function " + Math.max(10,40,20,30,5));

document.write("<br><br>Random Function " + Math.random());

document.write("<br><br>Logarithm Function " + Math.log(5));

</script>

</body>

10
</html>

Date Object:
• The Date object used to display the date on web page or time stamp in numerical or
mathematical calculations.
• Date objects are created with new Date ().
• There are five ways of instantiating (creating) a date:
var date1 = new Date();

or

var date1 = new


Date(milliseconds);
or

var date1 = new Date(“mm


dd, yyyy”); or

var date1 = new Date(“mm dd, yyyy


hr:min:sec”); or

var date1 = new Date(yyyy, mm, dd, [, hr, min, sec, millisec]);

properties:
Name Description
C onstructor Returns the function that created the Date object's prototype
P rototype Allows you to add properties and methods to an object

Methods

Name 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
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)
Returns the number of milliseconds since midnight Jan 1 1970, and a specified
getTime()
date
Returns the time difference between UTC time and local time, in minutes
getTimezoneOffset()

11
getUTCDate() Returns the day of the month, according to universal time (from 1-31)
getUTCDay() Returns the day of the week, according to universal time (from 0-6)
getUTCFullYear() Returns the year, according to universal time
getUTCHours() Returns the hour, according to universal time (from 0-23)
getUTCMilliseconds() Returns the milliseconds, according to universal time (from 0-999)
getUTCMinutes() Returns the minutes, according to universal time (from 0-59)
getUTCMonth() Returns the month, according to universal time (from 0-11)
getUTCSeconds() Returns the seconds, according to universal time (from 0-59)
now() Returns the number of milliseconds since midnight Jan 1, 1970
Parses a date string and returns the number of milliseconds since January 1
parse()
1970
setDate() Sets the day of the month of a date object
setFullYear() Sets the year of a date object
setHours() Sets the hour of a date object
setMilliseconds() Sets the milliseconds of a date object
setMinutes() Set the minutes of a date object
setMonth() Sets the month of a date object
setSeconds() Sets the seconds of a date object
Sets a date to a specified number of milliseconds after/before January 1, 1970
setTime()

setUTCDate() Sets the day of the month of a date object, according to universal time
setUTCFullYear() Sets the year of a date object, according to universal time
setUTCHours() Sets the hour of a date object, according to universal time
setUTCMilliseconds() Sets the milliseconds of a date object, according to universal time
setUTCMinutes() Set the minutes of a date object, according to universal time
setUTCMonth() Sets the month of a date object, according to universal time
setUTCSeconds() Set the seconds of a date object, according to universal time
setYear() Deprecated. Use the setFullYear() method instead
toDateString() Converts the date portion of a Date object into a readable string
Returns the date portion of a Date object as a string, using locale conventions
toLocaleDateString()

Returns the time portion of a Date object as a string, using locale conventions
toLocaleTimeString()

toLocaleString() Converts a Date object to a string, using locale conventions


toString() Converts a Date object to a string
toTimeString() Converts the time portion of a Date object to a string
toUTCString() Converts a Date object to a string, according to universal time

12
Returns the number of milliseconds in a date since midnight of January 1, 1970
UTC()
according to UTC time
valueOf() Returns the primitive value of a Date object

Example:
<html>

<body>

<h1>Date Object Get Methods</h1>

<script>

var dt = new Date();

document.write("<h3> Current Date and Time is <h1>" + dt + "</h1></h3>");

document.write("Full Year : " + dt.getFullYear());

document.write("<br><br>Time : " + dt.getTime());

document.write("<br><br> Month : " + dt.getMonth());

document.write("<br><br> Date : " + dt.getDate());

document.write("<br><br> Day : " + dt.getDay());

document.write("<br><br> Hours : " + dt.getHours());

document.write("<br><br> Minutes : " + dt.getMinutes());

document.write("<br><br> Seconds : " + dt.getSeconds());

document.write("<br><br> Milliseconds : " + dt.getMilliseconds());

</script>

</body>

</html>

5. Explain in detail about String & Array objects with


examples?
String Objects:
• String is a series of characters.
• String objects are used to perform operations on text.
• Syntax:
var variable_name = new String(string);
• Example:

13
var s = new String(string);
• String object properties
Properties Description
Length It returns the length of the string.
Prototype It allows you to add properties and methods to an object.
Constructor It returns the reference to the String function that created the object.
• String object methods
Methods Description

charAt() It returns the character at the specified index.

charCodeAt() It returns the ASCII code of the character at the specified position.

concat() It combines the text of two strings and returns a new string.

indexOf() It returns the index within the calling String object.

lastIndesOf() It returns the position of last occurrence of specified value in string.

match() It is used to match a regular expression against a string.

quote() It writes the quotes in JavaScript

replace() It is used to replace the matched substring with a new substring.

search() It executes the search for a match between regular expressions.

slice() It extracts a session of a string and returns a new string.

split() It splits a string into substrings.

toLowerCase() It returns the calling string value converted lower case.

toUpperCase() Returns the calling string value converted to uppercase.

fromCharCode() Converts Unicode to character.

substring() It returns the string between two specified indices.

toSource() It returns an object literal representing the specified object.

toString() It returns string representing the specified object.

valueOf() It returns the primitive value of a String object

Example:
<html>

<body>

<h1>String Methods</h1>

<script>

14
var str1=new String("Web Technologies");

var str2=new String("HTML");

var str3=new String("JAVASCRIPT");

var str4=new String(" CSS ");

document.write("charAt() Function : "+str1.charAt(5));

document.write("<br><br>charAt() Function : "+str1.charAt(30));

document.write("<br><br>charCodeAt() Function : "+str1.charCodeAt(5));

document.write("<br><br>charCodeAt() Function : "+str1.charCodeAt(105));

document.write("<br><br>concat() Function : "+str2.concat(" ",str3));

document.write("<br><br>After concat() Function str2 is : "+ str2);

document.write("<br><br>endsWith() Function : "+ str1.endsWith("ies"));

document.write("<br><br>includes() Function : "+ str1.includes("ing"));

document.write("<br><br>indexOf() Function : "+ str1.indexOf("e"));

document.write("<br><br>indexOf() Function : "+ str1.indexOf("z"));

document.write("<br><br>lastIndexOf() Function : "+ str1.lastIndexOf("e"));

document.write("<br><br>match() Function : "+ str1.match("e"));

document.write("<br><br>repeat() Function : "+ str1.repeat(2));

document.write("<br><br>replace() Function : "+ str1.replace("e","E"));

document.write("<br><br>replaceAll() Function : "+ str1.replaceAll("e","E"));

document.write("<br><br>search() Function : "+ str1.search("ies"));

document.write("<br><br>slice() Function : "+ str1.slice(1,10));

document.write("<br><br>slice() Function : "+ str1.slice(10));

document.write("<br><br>split() Function : "+ str1.split("e"));

document.write("<br><br>startsWith() Function : "+ str1.startsWith("e"));

document.write("<br><br>substr() Function : "+ str1.substr(5));

document.write("<br><br>substring() Function : "+ str1.substring(1,5));

document.write("<br><br>toLowerCase() Function : "+ str1.toLowerCase());

document.write("<br><br>toUpperCase() Function : "+ str1.toUpperCase());

document.write("<br><br>str4 : "+ str4.length);

document.write("<br><br>trim() Function : "+ str4.trim().length);

document.write("<br><br>str4 : "+ str4.length);

15
document.write("<br><br>trim() Function : "+ str4.trimEnd().length);

document.write("<br><br>str4 : "+ str4.length);

document.write("<br><br>trim() Function : "+ str4.trimStart().length);

</script>

</body>

</html>

Array object:
• An Array is used to store a number of values (called as elements) in order with a single
variable.
• An array object can created in two ways Using array constructor:
• Creates an empty array: var ar = new Array() Creates an array with given
size: var ar = new Array(size)
• Creates an array based on number of elements: var ar = new Array(element0, element1,
..., elementN)

Using array literal notation:


• Array literal notation are coma separated list of items enclosed by square brackets.
• creates an empty array: var ar = [ ]
• creates an empty array with elements: var ar = [ele1,ele2,...,elen ]
• example: var ar = [5,”hello”, true]

• Javascript Array Objects Property


Name Description
Length Returns the number of elements in an array
prototype Use to add new properties to all objects.
constructor Specifies the function which creates an object's prototype.

• JavaScript object methods:


Name Description
concat() Use to join two or more arrays and returns a new array.
join() Use to join all elements of an array into a string.
pop() Use to remove the last element from an array.
push() Use to add one or more elements at the end of an array.
reverse() Use to reverse the order of the elements in an array.
shift() Use to remove first element from an array.
slice() Use to extract a section of an array.
sort() Use to sort the elements of an array.
toString() Returns a string represent the array and its elements.

16
Use to add one or more elements to the beginning of an array and returns the new length of
unshift()
the array.
valueOf() Returns the primitive value of an array.

Example:
<html>

<body>

<h1>JavaScript Arrays</h1>

<h2>Array Methods</h2>

Concatenation <p id="c1"></p>

Join <p id="j1"></p>

POP Operation (removes last element of array) <p id="p1"></p>

After POP Operation arr1 is <p id="p2"></p>

Push Operation <p id="p3"></p>

After Push Operation arr1 is <p id="p4"></p>

Reverse of an array <p id="r"></p>

Shift operation (removes first element of array)<p id="s1"></p>

After Shift Operation arr1 is <p id="s2"></p>

Slice Operation<p id="s3"></p>

Before sort (arr2) <p id="s4"></p>

After sorting (arr2) <p id="s5"></p>

UnShift operation (adds new elements to array and returns new length)<p id="s6"></p>

After UnShift Operation arr2 is <p id="s7"></p>

to String (string is formed with coma separated elements of array) <p id="s8"></p>

Last Index <p id="li"></p>

<script>

var arr1 = [10,20.3,"hello",true,45];

var arr2 = new Array(30,20,10,40,50);

var arr3 = ["hello","welcome","to","javascript"];

var carray= new Array();

17
document.getElementById("c1").innerHTML = carray.concat(arr1,arr2);

document.getElementById("j1").innerHTML = arr3.join(" ");

document.getElementById("p1").innerHTML = arr1.pop();

document.getElementById("p2").innerHTML = arr1;

document.getElementById("p3").innerHTML = arr1.push(100,200);

document.getElementById("p4").innerHTML = arr1;

document.getElementById("r").innerHTML = arr1.reverse();

document.getElementById("s1").innerHTML = arr1.shift();

document.getElementById("s2").innerHTML = arr1;

document.getElementById("s3").innerHTML = arr1.slice(1,4);

document.getElementById("s4").innerHTML = arr2;

document.getElementById("s5").innerHTML = arr2.sort();

document.getElementById("s6").innerHTML = arr2.unshift(60,70);

document.getElementById("s7").innerHTML = arr2;

document.getElementById("s8").innerHTML = arr3.toString();

document.getElementById("li").innerHTML = arr3.lastIndexOf("welcome");

</script>

</body>

</html>

18

You might also like