3.1.4 Eventliseners For Event Handling
3.1.4 Eventliseners For Event Handling
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:
function secondFunction() {
alert("The second function executed successfully");
}
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:
function secondFunction() {
alert("The second function executed successfully");
}
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.
function setHoverColor() {
btn.style.background = "yellow";
}
function setNormalColor() {
btn.style.background = "";
}
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;
}
Output:
<html>
<body>
<script type="text/javascript">
alert("You are a Valid User !!!");
</script>
</body>
</html>
Output: