To remove the event listener from the button, you'll need to have a reference to the function itself. So before using addEventListener
store the function in an object or an array, or something where you can look back and find this function. Because removeEventListener
won't work if you don't give it the exact same function as you used with addEventListener
.
Down below in the code snippet I've constructed an example of a way to store these event listeners and call it an EventCollection
. This class functions as a container and holds a list of every event that you want to add. This way you can add or remove all the event listeners you want anytime in your code, without having to do too much work.
class EventCollection {
/**
* Create a list to store the entries in.
*/
constructor() {
this.entries = [];
this.isListening = false;
}
/**
* Add an entry to the collection to listen for on an event.
*/
append(target, type, listener, options = false) {
if (!(target instanceof EventTarget)) return;
this.entries.push({ target, type, listener, options });
return this;
}
/**
* Listen for all the entries in the list.
*/
listen() {
if (!this.isListening) {
this.entries.forEach(({ target, type, listener, options }) => {
target.addEventListener(type, listener, options);
});
this.isListening = true;
}
return this;
}
/**
* Stop listening for all the entries in the list.
*/
stopListening() {
this.entries.forEach(({ target, type, listener, options }) => {
target.removeEventListener(type, listener, options);
});
this.isListening = false;
return this;
}
}
// Create a new instance of an EventCollection
var eventCollection = new EventCollection();
var buttons = document.getElementsByTagName('button');
function myFunction(index) {
alert(index);
}
// Add all the event listeners to the collection.
for (var i = 0; i < buttons.length; i++) {
(function(i){
eventCollection.append(buttons[i], 'click', function() {
myFunction(i);
}, false);
}(i));
}
// Start listening.
eventCollection.listen();
// After 5 seconds, stop listening.
// The buttons won't work anymore.
setTimeout(function() {
eventCollection.stopListening();
}, 5000);
<button>Button 1</button>
<button>Button 2</button>
<button>Button 3</button>
Building the collection works like this. With the new
keyword.
// Create a new collection
var eventCollection = new EventCollection();
The next step is to add the event that you want to listen to. It needs the element, the type of event and the function to call when the event is triggered.
eventCollection.append(element, 'click', function() {});
Now your events are in the collection and stored, but they are not yet listening to the events. Use the .listen()
method to loop over all the events in the collection and listen for them.
eventCollection.listen();
And whenever you want to stop listening to events in your collection, then use the following.
eventCollection.stopListening();