In our starter files, open the index.html page from this lessons folder:
04.Events-And-The-DOM > 14.Removing-event-listeners
Earlier we looked at how to only run events once , then after they are removed.
We can also remove event listeners manually if they are no longer needed or used. This removal is not essential in smaller projects but for larger projects cleaning up old, unused event listeners can improve efficiency.
It also means we can use the same element to do different things, all by adding and removing event listeners to it. Over in the starter we have a very simple example:
<!-- index.html -->
<body>
<button id="add">add</button>
<button id="cancel">cancel</button>
<span>Score:</span><p>0</p>
<script src="events.js"></script>
</body>
There is a score section, a button to increase the score, and a cancel button. The purpose here is to increase the score when we click add, and then the cancel button will remove the event listener.
In the events.js
file we have a reference to these 3 elements:
const add = document.querySelector('#add');
const cancel = document.querySelector('#cancel');
const output = document.querySelector('p');
First, we need to create an event listener to call a function. This function will add to the current total:
function increase() {
// a log will show the innerText content is a string:
console.log(typeof output.innerText);
// therefore we need to convert this string to a number with Number()
output.innerText = Number(output.innerText) +1;
}
add.addEventListener('click', increase);
Now we also need to listen out for a click on the cancel button:
function stopListener() {
console.log('cancel');
}
cancel.addEventListener('click', stopListener);
removeEventListener
methodTo get this function to stop the add button working we have a method called removeEventListener
. We want to remove the event on the add button, so we call it on this, inside of our function:
function stopListener() {
console.log('cancel');
add.removeEventListener("click", increase);
}
Clicking the cancel button will now stop the add button from adding. There is something to watch out for too. Here we are adding and removing the exact same event listener:
add.addEventListener('click', increase);
add.removeEventListener('click', increase);
It works because the information in the brackets is the same. We are matching the same event type, which is click, and cancelling the same function. And this is important for it to be cancelled. They must be identical.
Even if they call the same function, we couldn’t have two different event types like this:
add.addEventListener('mouseover', increase);
add.removeEventListener('click', increase);
Also, passing in the capture option will cause them to not match:
add.addEventListener('click', increase, {capture: true})
add.removeEventListener('click', increase)
After adding the capture phase, cancelling it won’t work. Since it has different options, it is considered a different event.