How to Add and Remove Event Listener in Javascript

In this tutorial, you will learn how to add and remove event listener in javascript. Events play a very important role in javascript.  There are a lot of built-in events in javascript.

You can also create your custom events using Event and CustomEvent constructors.  Events get fired when a user interacts with a web page such as click on a button, pressing keyboard keys, moving the mouse, etc.

You can execute a certain piece of code when a particular event is fired.  This piece code should be inside an event handler function. To accomplish this, you have to attach that event to an element.

In some situations, you may want to detach an event and prevent the execution of the event handler function.  That is also possible in javascript.  We can attach an event to the element using addEventListener() function and detach an event using removeEventListener() function.

In the following example, we have 2 buttons to attach and detach a mousemove event.  The event will be attached to the document.  We also have an h1 element to display mouse coordinates.  Please have a look over the code example and steps given below.

HTML & CSS

  • We have 4 elements in the HTML file (div, 2 button, and h1). The div element is just a wrapper for the rest of the elements.
  • The first button element has “Add” and the second button element has “Remove” as inner text.
  • The inner text for the h1 element is “Output” and that will be later replaced by javascript with mouse coordinates.
  • We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="style.css">
    <title>Document</title>
</head>
<body>
    
    <div>
        <button id="add">Add</button>
        <button id="remove">Remove</button>
        <h1>Output</h1>
    </div>

    <script src="script.js"></script>
</body>
</html>
body {
    text-align: center;
}

div {
    display: inline-block;
}

button {
    padding: 10px 20px;
}

Javascript

  • We have selected both the button elements by their ids and the h1 element by its tag name using the document.querySelector() method and stored them in btnAdd, btnRemove, and output variables.
  • We have attached the click event listener to both the button elements.
  • We have created the handleEvent() function which will act as our event handler. Inside this function, we are simply setting the inner text of the h1 element to display mouse coordinates.
  • Inside the event handler function of the first button btnAdd, we are attaching mousemove event listener to the document.
  • Inside the event handler function of the second button btnRemove, we are detaching mousemove event listener from the document.
let btnAdd = document.querySelector('#add');
let btnRemove = document.querySelector('#remove');
let output = document.querySelector('h1');

btnAdd.addEventListener('click', () => {
    document.addEventListener('mousemove', handleEvent);
});

btnRemove.addEventListener('click', () => {
    document.removeEventListener('mousemove', handleEvent);
});

function handleEvent(e){
    output.innerText = `X: ${e.pageX} - Y: ${e.pageY}`;
};