In this lesson, we'll discuss addEventListener()
and removeEventListener()
, which are used to assign and remove event handlers, respectively.
Consider the following HTML code:
<!DOCTYPE html><html><head> <title>Lesson 48</title></head><body> <div id="container"> <button id="btn">Click Me</button> </div> <script src="script.js"></script></body></html>
In the script.js
file, we can add event listeners to the button using the addEventListener()
method. For example:
const btn = document.getElementById('btn'); btn.addEventListener('click', function(e){ alert("Hello World!");}); btn.addEventListener('click', function(e){ alert("Hello World Again!");});
When the button is clicked, the browser will execute the code inside the event handler function. In this case, the browser will display two alert boxes with the messages "Hello World!" and "Hello World Again!".
Both event listeners will be executed when the button is clicked. We can also define the functions separately and then add event listeners to them
const x = function(e){ alert("Hello World!");}; const y = function(e){ alert("Hello World Again!");}; btn.addEventListener('click', x);btn.addEventListener('click', y);
If we want to remove an event listener, we can use the removeEventListener()
method. For example, assume we want to log to the console only once if the user's favorite number is 1:
const ask = prompt("What is your favorite number?"); const x = function(e){ alert("Hello World!");}; const y = function(e){ alert("Hello World Again!");}; btn.addEventListener('click', x);btn.addEventListener('click', y); if (ask === "1"){ btn.removeEventListener('click', y);}
In this case, the browser will display only one alert box with the message "Hello World!" if the user's favorite number is 1. Otherwise, the browser will display two alert boxes with the messages "Hello World!" and "Hello World Again!".
event object
Now, let's talk about the event object. When an event occurs, the browser creates an event object and passes it as an argument to the event handler. We can access this event object using a parameter in the event handler function. For example:
const x = function(e){ console.log(e); alert("Hello World!");};
The event object contains a lot of details that may be useful in some cases. For example, we can log the event type, client X and Y coordinates using the event object:
const x = function(e){ console.log(e.type, e.clientX, e.clientY); // click 29 70 (values will change depending upon where u clicked the button)};
However, if we don't need the event object, we can simply omit it from the function definition:
const x = function(){ alert("Hello World!");};
We can also use our own variable names instead of the default "e":
const x = function(myOwn){ alert("Hello World!"); console.log(myOwn);};