DONATE  
MENU
AJAX
HTML
JSON
JAVASCRIPT

JavaScript Tutorials

INTRODUCTION

» Introduction to JavaScript

» Practice IT Editor

» JavaScript Example

» JavaScript Placement

» JavaScript Syntax

» JavaScript Statements

» JavaScript Input

» JavaScript Output

» JavaScript Comments

» JavaScript Variables

» Variables' Scope

» JavaScript Operators

» JS Expressions & Concatenation

» JavaScript Data Type

» JavaScript Numbers

» Number Object

» JavaScript Strings

» String Object

» JavaScript Booleans

» Boolean Object

» JavaScript Functions

» JavaScript Arrays

» Array Object - Properties

» Array Object - Methods

» JavaScript Objects

» JavaScript Undefined

» JavaScript Nulls

CONDITIONAL TESTING

» If Statement

» If Else Statement

» JavaScript Ternary Operator

» Switch Statement

LOOPS

» For Loops

» While Loops

» Break & Continue

» For...In Loops

» do...while Loop

FUNCTIONS

» JavaScript Functions

» Creating Functions

» Functions' Parameters

» Functions' Arguments

» Function Invocation

» The Return Keyword

» The Arguments Object

» Callback Functions

» Arrow Functions

ARRAYS

» JavaScript Arrays

» Creating Arrays

» Accessing Arrays

» Looping Arrays

» Multi - dimensional Arrays

OBJECTS

» JavaScript Objects

» Creating Objects

» Prototype Definition

» Accessing Objects

» The this Keyword

AJAX

» Introduction to AJAX

JSON

» Introduction to JSON

JAVASCRIPT DATES

» The Date Object

» Date Methods

» Timing (SetInterval & SetTimeout)

MATH OBJECT

» Math Object

» Math Methods

HTML / JS DOM

» DOM Introduction

» Accessing HTML Elements in DOM

» Get And Change Elements' Contents & Values

» Change Styling - DOM CSS

» DOM Attributes

» JavaScript Event Listeners

» DOM Event Listeners

» JS Events

MISCELLANEOUS

» JS Strict Mode

» JavaScript Hoisting

» JavaScript let keyword

» Reserved Keywords

» JS Best Practices

» JavaScript vs ECMAScript

JAVASCRIPT EXAMPLES

» JavaScript Calculator

.. » JavaScript » Html / Js Dom » DOM Event Listeners
Share Tweet WhatsApp

DOM Event Listeners

On this page, you shall continue familiarizing yourself with various ways event handlers can be created. The object of every element in the document object have various methods that can be used in assigning handlers to events when they happen. Some of such methods are: addEventListener() The addEventListener() method is a method of every element's object in the document object. It enables us to add event listeners to the elements of a webpage. It's arguments should basically be the event and the callback function to execute when such events happen. You may decide to specify a third argument representing the event propagation method.
<button id='btn'>Click Me</button>

<script>
var btn = document.getElementById("btn");//Accesses element and stores element object on a variable

btn.addEventListener("click", clickMe); //Calling a method of the element object to add the event listener to the element

//The function to execute for the event when it happens
function clickMe(){
alert("You clicked a button");
}
</script>

Copy PRACTICE IT

Remember, when passing a callback function as an argument to a function, only the name of the function should be specified. There should be no parentheses (()). Know more about callback functions in the callback functions tutorial. If the callback function for the event has parameters, then we need to create an anonymous function inside the addEventListener() and invoke the callback function inside the function.
<p style='white-space:pre-line;' id='mytext'></p>
<center><p><textarea id='text' placeholder='Type something' rows='10' style='width:100%;'></textarea></p><center>

<script>
document.getElementById("text").addEventListener("keyup", /* The Function */ function(){
output(this); //Calling callback function with parameter
});

function output(text){
document.getElementById("mytext").innerHTML = text.value;
}
</script>

Copy PRACTICE IT

<button>CLICK ME</button>

<script>
var btn = document.getElementsByTagName("button")[0];

btn.addEventListener("click", function (){
findMax(1, 4, 2, 5, 4, 1);
});

function findMax(){
var max = arguments[0];
var len = arguments.length;

for (var i=0; i<len; i++)
{
if (arguments[i] > max){
max = arguments[i];
}
}
alert("The maximum number is "+max);
}
</script>

Copy PRACTICE IT

EXPLAINED The function to execute for the above events needed parameters to perform the action they were created for e.g the findMax() function which needed some numbers in its parameter to find the highest or maximum. Since, when passing callback functions as arguments to functions and methods, you don't need to add parentheses (()) meanwhile arguments are specified in parentheses, we therefore need to create an anonymous function in place of the callback function name and inside that function, we can then call our callback function with parentheses thereby allowing us to specify arguments. Also, using the above anonymous function logic, we can directly specify in the addEventListener method, statements to execute when the event happens.
<button>CLICK ME</button>

<script>
var btn = document.getElementsByTagName("button")[0];

btn.addEventListener("click", function(){
var sum = 3 + 5;  //statement
alert(sum); //statement
});
</script>

Copy PRACTICE IT

Or even create and call functions inside the anonymous function,
<button>CLICK ME</button>
<script>
var btn = document.getElementsByTagName("button")[0];

btn.addEventListener("click", function(){
function myFunc(num1, num2){
var sum = num1 + num2;
alert(sum);
}
myFunc(55, 6);
});
</script>

Copy PRACTICE IT

And yes, invoke multiple functions when an event happens,
<button>CLICK ME</button>
<script>
var btn = document.getElementsByTagName("button")[0];

btn.addEventListener("click", function(){
myFunc1();
myFunc2();
myFunc3();
});

function myFunc1(){
alert("This is from function 1");
}

function myFunc2(){
alert("This is from function 2");
}

function myFunc3(){
alert("This is from function 3");
}

</script>

Copy PRACTICE IT

removeEventListener() The removeEventListener() method enables us to remove event listeners added with the addEventListener() method from an element.
<button id='btn'>Click Me</button>

<script>
var btn = document.getElementById("btn");
btn.addEventListener("click", clickMe, true);
btn.removeEventListener("click", clickMe, true);
function clickMe(){
alert("You clicked me");
}
</script>

Copy PRACTICE IT

NOTE:
  • The removeEventListener() should be compose just the way the event was added with the addEventListener().
    element.addEventListener("click", myFunc, true);
    element.removeEventListener("click", myFunc); //Won't work
    element.addEventListener("click", myFunc, true); //Will work
    //All these to ensure the right event is being remove
To remove events with anonymous functions such as,
element.addEventListener("click", function (){
addNum(3,4);
});
We need to define such anonymous function on a variable and use the variable both on the addEventListener() and removeEventListener().
<button id='btn'>Click Me</button>

<script>
var myFunc = function (){
addNum(3,4);
};

var btn = document.getElementById("btn");
btn.addEventListener("click", myFunc, true);
btn.removeEventListener("click", myFunc, true);
function addNum(x,y){
alert(x+y);
}
</script>

Copy PRACTICE IT

EVENT PROPAGATION: BUBBLING AND CAPTURING Event propagation is the order in which event handlers should execute when an event takes place. For example, assuming a paragraph element with a click event handler also has in it a button element with a click event handler, which handler should be handled first when a click event finally takes place? The button handler or paragraph handler. Event bubbling means the order should start from the inner element to the outer element i.e from the button handler to the paragraph handler. This is the default method of event propagation.
<p onclick='pclick()'><button onclick='btnclick()'>Click Me</button></p>

<script>
function pclick(){
alert("Paragraph element");
}

function btnclick(){
alert("Button element");
}
</script>

Copy PRACTICE IT

On the contrary, event capturing goes for the execution from the outer handler to the inner handler. That is from the paragraph handler to the button handler. The third parameter(useCapture) of the addEventListener() method allows us to specify the event propagation method to use. If its argument is false, then the event bubbling propagation is used else event capturing.
element.addEventListener("click", myFunc, true); //event capturing
element.addEventListener("click", myFunc, false); //event bubbling
<p><button>Click Me</button></p>

<script>
document.getElementsByTagName("p")[0].addEventListener("click", pclick, true);
document.getElementsByTagName("button")[0].addEventListener("click", btnclick, true);
function pclick(){
alert("Paragraph element");
}

function btnclick(){
alert("Button element");
}
</script>

Copy PRACTICE IT

setAttribute() Since the setAttribute() method is used in assigning attributes to elements, you can also use it to set event handlers as well.
<button id='btn'>Click Me</button>

<script>
var btn = document.getElementById("btn");

btn.setAttribute("onclick", "myFunc()");

function myFunc(){
alert("You clicked me");
}
</script>

Copy PRACTICE IT

SUMMARY
  1. Every object of elements contained in the document object has methods that help assign event handlers to elements.
  2. One of such is the addEventListener(). The arguments to pass to it should be the event to handle, the function definition to execute and finally, the propagation method to apply.
  3. Events added to elements using the addEventListeners() can be removed using the removeEventListeners() method.
  4. The arguments to pass to the removeEventListener() should be same passed when using the addEventListener()
  5. Event propagation is the order in which event handlers should be executed.
  6. Event bubbling is a method of event propagation that favours the execution of the innermost event handlers to the outer handlers. It is the default method.
  7. Event capturing is the opposite of event bubbling. Execution starts from the outer handler to the inner handler.
  8. The setAttribute() method also enables to assign or remove event attributes.
Take a short quiz on DOM Event Listeners.
Ask a question or tell us if DOM Event Listeners is easy or not.
cent?

Join our 1,090 subscribers to receive tutorials' updates!

  We won't spam your mail box. We hate it.





StackBeginner 2021 © Joseph Omamode