3.1.4 Eventliseners For Event Handling

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 8

3.1.

4 EventLiseners for Event Handling

The EventTarget interface provides us with multiple methods that can be used for handling the events in
javascript on DOM objects. One of the most important methods of EventTarget interface is addEventListener()
which helps to create and define the snippet execution on the occurrence of the particular event. These events
can be defined not only on the elements of HTML but also on the window object itself. These events can also be
defined on the event supporting objects like AudioNode, AudioContext, XMLHttpRequest.

It is very easy to add an event to any object in javascript by using addEventListener(). We can even add multiple
event listeners to a single object that too of the same type. These events will not override each other and will
execute properly as expected without affecting each other’s working.

The event listeners are just like event handlers, except that you can assign as many event listeners as you like to
a particular event on particular element.
To understand how event listeners actually works let's check out a simple example. Suppose that you've created
two functions and you try to execute both of them on click of the button using the onclick event handler, as
shown in the following example:

<button id="myBtn">Click Me</button>


<script>
// Defining custom functions
function firstFunction() {
alert("The first function executed successfully!");
}

function secondFunction() {
alert("The second function executed successfully");
}

// Selecting button element


var btn = document.getElementById("myBtn");

// Assigning event handlers to the button


btn.onclick = firstFunction;
btn.onclick = secondFunction; // This one overwrite the first
</script>

When above example is run and click the button element, only secondFunction() will be executed, because
assigning the second event handler overwrites the first.
This is the main shortcoming of this classic event model—you can only assign one event handler to a particular
event on a particular element i.e. a single function per event per element. To deal with this problem W3C
introduced more flexible event-model called event listeners.
Any HTML element can have multiple event listeners, therefore you can assign multiple functions to the same
event for the same element, as demonstrated in following example:

<button id="myBtn">Click Me</button>


<script>
// Defining custom functions
function firstFunction() {
alert("The first function executed successfully!");
}

function secondFunction() {
alert("The second function executed successfully");
}

// Selecting button element


var btn = document.getElementById("myBtn");

// Assigning event listeners to the button


btn.addEventListener("click", firstFunction);
btn.addEventListener("click", secondFunction);
</script>

Now, if on running above example and click the button, both functions will be executed.
In addition to the event type and listener function parameter the addEventListener() accepts one more Boolean
parameter useCapture. This is an optional parameter which specifies whether to use event bubbling or event
capturing. Its basic syntax is:
target.addEventListener(event, function, useCapture);

The above syntax is explained in detail below by describing each of its content variables:
 Element: It can be any element in current DOM or object that supports event handling like window or
XMLHttpRequest.
 Event: It is a case-sensitive string that specifies the occurrence of which the specified action is to be
performed. Examples of such events are click, dbclick, mouseover, mousemove, etc. Caution should be
taken while specifying the event as this string is case-sensitive and needs a correct word for the proper
execution of these events.
 functionName: This function defines the actual code you want to execute when the above-mentioned
event will occur. This function can be either named or anonymous. We will see the example of both of
these methods of declaring functions in further part.
 useCapture: This is a Boolean parameter which is by default set to false. This specifies whether the
nature of event execution while parent-child structure will be event capturing or bubbling. If we want
to capture event execution type, we can send this parameter as true while in all other cases it will show
bubbling type of nature while event execution. We will see this working and difference between both of
them clearly with the help of examples further.

Adding Event Listeners for Different Event Types


Like event handler, you can assign different event listeners to different event types on the same element. The
following example will assign different event-listener functions to the "click", "mouseover", and "mouseout"
events of a button element.
Example:
<button id="myBtn">Click Me</button>
<script>
// Selecting button element
var btn = document.getElementById("myBtn");

// Defining custom functions


function sayHello() {
alert("Hi, how are you doing?");
}

function setHoverColor() {
btn.style.background = "yellow";
}

function setNormalColor() {
btn.style.background = "";
}

// Assigning event listeners to the button


btn.addEventListener("click", sayHello);
btn.addEventListener("mouseover", setHoverColor);
btn.addEventListener("mouseout", setNormalColor);
</script>

Example2:

<!DOCTYPE html>
<html>
<body>
<p>This example will demonstrate the working of addEventListener by calling
a method to alert a message when the button is clicked</p>
<button id="demoButton">Greetings for today</button>
<script>
document.getElementById("demoButton").addEventListener("click", function(){
alert("Good Morning! Have a great day ahead.");
});
</script>
</body>
</html>

Output:
Adding Event Listeners to Window Object
The addEventListener() method allows you to add event listeners to any HTML DOM elements, the document
object, the window object, or any other object that support events, e.g, XMLHttpRequest object. Here's an
example that attaches an event listener to the window "resize" event:
Example:
<div id="result"></div>

<script>
// Defining event listener function
function displayWindowSize() {
var w = window.innerWidth;
var h = window.innerHeight;
var size = "Width: " + w + ", " + "Height: " + h;
document.getElementById("result").innerHTML = size;
}

// Attaching the event listener function to window's resize event


window.addEventListener("resize", displayWindowSize);
</script>

Passing the Parameters


Passing the parameters to the function being called when the event occurs can only be done by calling a
method which in turn will call another method with parameters. Example where addEventListener write and
call an anonymous method inside which will be called the actual method whose execution I want to perform on
event occurrence and pass the required parameters to it.
Example:
<!DOCTYPE html>
<html>
<body>
<p>These methods demonstrate how parameters can be passed in
addEventListener by calling a method which in turn will call our desired
method with parameters</p>
<p id="multipliedResult"></p>
<button id="demoButton">Test it</button>
</body>
<script type="text/javascript">
document.getElementById("demoButton").addEventListener("click", () =>
{ multiplyNumbers(15, 27);
});
function multiplyNumbers(a, b) { var multipliedValue = a * b;
document.getElementById("multipliedResult").innerHTML = multipliedValue;
}
</script>
</html>
Output:

Event Bubbling and Capturing


Suppose there is a div element with id outerElement and paragraph p element inside the div outerElement with
id innerElement. If we declare a click eventlistener on both and click the child element paragraph then which
event will execute first, its parent division’s or the child itself is decided by third optional parameter to
eventListener is a capture.
If it’s capturing then parent’s i.e div element’s event listener will be called while in case of bubbling child’s
paragraph element’s event listener will be called first and then the other.

Removing Event Listeners


You can use the removeEventListener() method to remove an event listener that have been previously attached
with the addEventListener(). Here's an example:

<button id="myBtn">Click Me</button>


<script>
// Defining function
function greetWorld() {
alert("Hello World!");
}

// Selecting button element


var btn = document.getElementById("myBtn");

// Attaching event listener


btn.addEventListener("click", greetWorld);

// Removing event listener


btn.removeEventListener("click", greetWorld);
</script>

3.1.5 Event Handling: A Code Snippet


Event Handling is a software routine that processes actions, such as keystrokes and mouse movements. It is the
receipt of an event at some event handler from an event producer and subsequent processes.

Functions of Event Handling


 Event Handling identifies where an event should be forwarded.
 It makes the forward event.
 It receives the forwarded event.
 It takes some kind of appropriate action in response, such as writing to a log, sending an error or
recovery routine or sending a message.
 The event handler may ultimately forward the event to an event consumer.

Example: Simple Program on onload() Event handler


<html>
<head>
<script type="text/javascript">
function time()
{
var d = new Date();
var ty = d.getHours() + ":"+d.getMinutes()+":"+d.getSeconds();
document.frmty.timetxt.value=ty;
setInterval("time()",1000)
}
</script>
</head>
<body onload="time()">
<center><h2>Displaying Time</h2>
<form name="frmty">
<input type=text name=timetxt size="8">
</form>
</center>
</body>
</html>

Output:

Example: Simple Program on onsubmit() & onfocus() Event handler


<html>
<body>
<script>
function validateform()
{
var uname=document.myform.name.value;
var upassword=document.myform.password.value;
if (uname==null || uname=="")
{
alert("Name cannot be left blank");
return false;
}
else if(upassword.length<6)
{
alert("Password must be at least 6 characters
long.");
return false;
}
}
function emailvalidation()
{
var a=document.myform.email.value
if (a.indexOf("@")==-1)
{
alert("Please enter valid email address")
document.myform.email.focus()
}
}
</script>
<body>
<form name="myform" method="post" action="validpage.html"
onsubmit="return validateform()">
Email: <input type="text" size="20" name="email"
onblur="emailvalidation()"><br>
User Name: <input type="text" name="name"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Submit" >
</form>
</body>
</html>

validpage.html //File name

<html>
<body>
<script type="text/javascript">
alert("You are a Valid User !!!");
</script>
</body>
</html>

Output:

You might also like