There are some circumstances in which you will only want to perform a certain action one time and one time only. One example being when a user clicks on the 'submit' button when making a payment. While you could remove the button from the DOM entirely to prevent a double-click, you might need re-render the button in case something goes wrong.
This is where removeEventListener() comes into play.
removeEventListener() allows you to selectively remove any type of event from an element.
function loadEvents(){
let button = document.getElementById('button-submit');
button.addEventListener('click', submit);
}
function submit(){
console.log('submit');
let button = document.getElementById('button-submit');
button.removeEventListener('click', submit);
}
The removeEventListener() method takes 2 arguments, both matching the same arguments that addEventListener() takes as well.
Note that removeEventListener() and addEventListener() are not supported in IE8 or older.
In those particular cases you can use the attachEvent() and detachEvent() methods instead.
Checking for browser support
You can use the following to check for browser support:
function loadEvents(){
let button = document.getElementById('button-submit');
if (button.addEventListener)
button.addEventListener('click', submit);
else
button.attachEvent('onclick', submit);
}