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

JavaScript Functions and Events Guide

The document provides an overview of JavaScript functions and events, explaining how functions perform tasks and how events trigger actions in web pages. It covers various aspects such as function parameters, scope, closures, and built-in events like onclick and onload. Additionally, it details timer functions like setTimeout and setInterval for executing code after specified intervals.

Uploaded by

Amisha Sharma
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 views24 pages

JavaScript Functions and Events Guide

The document provides an overview of JavaScript functions and events, explaining how functions perform tasks and how events trigger actions in web pages. It covers various aspects such as function parameters, scope, closures, and built-in events like onclick and onload. Additionally, it details timer functions like setTimeout and setInterval for executing code after specified intervals.

Uploaded by

Amisha Sharma
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

JavaScript Functions, Events,

JavaScript allows you to create interactive Web pages by providing various


functions and events.
A function is a set of statements used to perform a particular task. The set of
statements in a function are executed when the function is called in a
program.

In JavaScript, you can create a function that accepts input (for example,
name) from a user and displays it whenever the user visits the same Web
page in which the function is defined.

You can also create JavaScript functions to perform various tasks, such as
calculating numbers or displaying text in a control.

Events in JavaScript are actions that are executed when you perform certain
tasks. For example, you can use events to display a welcome message when a
user submits a form.

JavaScript provides various built-in events, such as the onclick event that
triggers when you click a button, the onload event that triggers when a Web
page is loaded, and the onmousedown event that triggers on clicking the
mouse button
Working with Functions
<html>
<head>
<SCRIPT type="text/javascript">
function simple()
{
alert("This is an alert box. Thank You!!")
}
</script>
</head>

<BODY onload="simple()">
<H1>Using Simple JavaScript Function</H1>
<P>Here we are using a simple JavaScript function that displays an alert
box on the load event of the Web page.</P>
</BODY>
</html>
Working with Functions
A function contains code that is executed when an event is triggered or the
function is called. You can call the function from anywhere within a program.
You can also define the parameters to be passed with functions while calling
the function.

Scope of a function:
A scope refers to an area within which a function and its variables are
accessible. Each function is associated with a scope, which defines its
accessibility in a program.
In JavaScript, scope of a function is divided into the following two categories:
• Global—Specifies that a function can be called or accessed from anywhere in
a program
• Local—Specifies that a function can be accessed only within its parent
function

A closure is a variable that is created inside a function and continues to exist


after the function has finished executing. It is a combination of two things, a
function and any local variable defined in that function. Closures are used in
defining control structures, such as branches and loops.
Calling Functions with Timer
Timer is one of the most important features of JavaScript, which allows you to
execute JavaScript functions after a specified period; thereby, making it possible to
add a new dimension, time, to your Web pages.

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

To use timer, JavaScript provides various methods:


The setTimeout() method—Executes code at a specified interval.
Syntax of the setTimeout() method:
setTimeout(function, delayTime)
The function parameter specifies the method that the timer calls and the delayTime
parameter specifies the number of milliseconds to wait before calling the method.

The clearTimeout() method—Deactivates or cancels the timer that is set using the
setTimeout() method.
Syntax of the clearTimeout() method:
clearTimeout(timer)
timer is a variable that is created using the setTimeout() method.
Calling Functions with Timer
The setInterval() method—Executes a function after a specified time
interval.
Syntax of the setInterval() method:
setInterval(function, intervalTime)
The function parameter specifies the method to be called; whereas, the
intervalTime parameter specifies the time interval between the function calls.

In terms of execution, settimeout gets executed only ONCE after the


specified time out period has elapsed, whereas setinterval gets executed in
a repeated manner after the specified time period as per the argument is
elapsed.

The clearInterval() method—Deactivates or cancels the timer that is set


using the setInterval() method.
Syntax of the clearInterval() method:
clearInterval(timer)
The preceding syntax deactivates the timer variable that is created using the
setInterval() method.
Events
Events refer to actions that are detected by a programming language
when you perform a particular task.
For example, the onclick event is detected by the programming
language when you click the mouse button.

Events are generally used in combination with functions, implying that


when an event occurs, it calls a specified function.

An event commonly occurs when a user clicks the mouse button, Web
page is loaded, or form field is changed.

Events are handled by a special function, known as event handler, which


handles a particular event when the event is triggered.
Function with parameters
A function with parameters accepts some values when it is called.

<html>
<head>
<SCRIPT type="text/javascript">
function parameter(value)
{
alert("This is an alert box." + value)
}
</script>
</head>

<BODY>
<FORM>
<INPUT type="button" onclick="parameter('JavaScript function with parameter')" value="Call
function"> </FORM>
<P>This is an example of JavaScript function with parameters</P>
</BODY>
</html>

we have created the parameter() function that contains value as a parameter. The value of the
parameter and code for passing the parameter to the function are provided under the FORM element.
The value of the parameter is enclosed in single quotes. We have also created the Call function button
which when clicked calls the parameter() function. The Web browser then identifies the variable value
as a parameter and displays the value of the parameter as a message in the alert box.
Function arguments
<html>
<BODY>
<SCRIPT type="text/javascript">
function total(a,b,c)
{
var sum = a+b+c;
[Link]("total = "+ sum);
}
[Link]("The sum is calculated by passing arguments to the
function<BR/>");
total(4,5,6);
</script>
</BODY>
</html>
Using a return statement
The return statement returns a value from a function.

<html>
<BODY>
<SCRIPT language="JavaScript">
function area (l, b)
{
var rectangle = l*b;
return rectangle;
}
var rect=area (4,6);
[Link]("Area of rectangle is: "+rect);
</SCRIPT>
</BODY>
</html>
Function Scope and Closures
the scope of a function specifies its accessibility within a program.
<html>
<BODY>
<SCRIPT language="JavaScript">
// call function to display greeting message
Showmessage();
// "Hello, World" function
function Showmessage()
{
// declaring new variables
var date = new Date();
var hour = [Link]();
var min = [Link]();
var month = [Link]() + 1
var day = [Link]()
var year = [Link]()
// call DisplayGreeting
Display();
// display greeting
function Display()
{
if (hour >= 22 || hour <= 5)
[Link]("Goodnight, world! <BR/>");
else
[Link]("Hello, world! <BR/>");
[Link] ("Today is " + month +"/" + day + "/" + year + "<BR/>");
[Link] ("The current time is " + hour +":" + min);
}
}
//Display();
</SCRIPT>
</BODY>
</html>
Function Scope and Closures
We have created a function, named Display(), inside the Showmessage()
function.
The scope of the Display() function is limited only within the
Showmessage() function.
Whereas, the Showmessage() function can be accessed througout a
program.
The Showmessage() function acts as a closure as it combines two things,
a function and a local variable.
setTimeout() Method
the setTimeout() method is used to specify the time interval after which the code executes.
This method is useful in the situation when you want to delay the execution of a particular
code.

<HTML>
<HEAD>
<SCRIPT type="text/javascript">
function timedMsg()
{
var t=setTimeout("alert('3 seconds!')",3000);
}
</SCRIPT>
</HEAD>
<BODY>
<FORM> <INPUT type="button" value=" timed alert box!" onClick="timedMsg()" />
</FORM>
</BODY>
</HTML>

the setTimeout(“alert (‘3 seconds!’)”, 3000) method is used to create a timed alert box. The
first parameter of the setTimeout() method is a string that contains a JavaScript statement,
alert(‘5 seconds!’), and the second parameter, 5000, specifies the time in milliseconds after
which the first parameter will be executed.
setInterval() Method
the setInterval() method is used to execute the code after every specified time intervals.

<HTML>
<HEAD>
<SCRIPT type="text/javascript">
function timedMsg()
{
var t=setInterval("alert('2 seconds!')",2000);
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<INPUT type="button" value=" timed alert box!" onClick="timedMsg()" />
</FORM>
</BODY>
</HTML>

the setInterval() method is used to create a timer that calls the alert() method repeatedly. In the
setInterval() method, the first parameter is a string that contains a JavaScript statement, alert (‘2
seconds!’). The second parameter specifies the time in milliseconds, 1000, after which the first
parameter is displayed.

when the user clicks the timed alert box! button, it displays a timed alert box after every 1 second.
Onclick Event
The onclick event triggers when you click a particular control, such as
the button control.

<HTML>
<body>
<FORM name="form">
Name:<INPUT type="text" id="field" value=" " ><BR/>
<BUTTON onclick="alert('Welcome, ' +
[Link]('field').value)">Click me</BUTTON>
</FORM>
</body>
</HTML>

you can see an alert box that appears due to the occurrence of the
onclick event. This event occurs when the Click me button is clicked.
Onload Event
The onload event triggers when a Web page loads in a browser. In
HTML, this event is defined in the BODY element.

<HTML>
<BODY onload = "alert ('Welcome to javascript!')">
<P>This example displays an alert box at the load event of the Web
page.</P>
</BODY>
</HTML>

we have defined the onload event in the BODY element, which displays
an alert box showing the text, Welcome to javascript!, when a Web
page loads.
Mouse Event
The mouse events are those events that trigger while operating the
mouse.
<HTML>
<BODY>
<P> click this Button </P>
<BUTTON onmousedown = "[Link]['img'].src='[Link]'"
onmouseup = "[Link]['img'].src='[Link]'" >
<IMG NAME="img" >
CLICK ME
</BUTTON>
</BODY>
</HTML>
Mouse Event
We have defined the onmousedown and onmouseup events in the
BUTTON element. These events change the image of the button control
when you press the mouse button and release it.

When you click and hold down the mouse button, an image appears on
the button.

The image appears on the button control until you release the mouse
button.

As soon as you release the mouse button, an image of car that we have
specified in the onmouseup event appears on the button.
Onreset Event
The onreset event is defined with a form and is triggered when the fields of form are
reset.
<HTML>
<BODY>
<FORM onreset="alert('onreset event is triggered when the user clicks the RESET
button')">
<B>Name:</B>
<INPUT type="text" name="fname" value=" ">
<BR>
<B>Roll Number:</B>
<INPUT type="text" id="fnumber" value=" ">
<BR>
<BR>
<INPUt type="reset" value="RESET">
</FORM>
</BODY>
</HTML>

we have defined the onreset event in the FORM element, which displays some text
in an alert box when the form fields are reset.
On clicking the RESET button, an alert box appears,
Onsubmit Event
The onsubmit event is used with the FORM element and is triggered when the
form is submitted.
<HTML>
<BODY>
<FORM onsubmit ="alert('All the details of this form are submitted')">
<B>Name:</B>
<INPUT type="text" name="fname" value="">
<BR>
<B>Roll Number:</B>
<INPUT type="text" id="fnumber" value="">
<BR>
<INPUT type="submit" value="SUBMIT">
</FORM>
</BODY>
</HTML>

we have defined the onsubmit event in the FORM element, which displays
some text in an alert box when the form is submitted.
fill all the fields of the form and click the SUBMIT button. An alert box
appears,

You might also like