ProgrammingJavascriptCareerProductivityGadgetsASP.NETWeb Design

How to remove event handlers with removeEventListener()

Written by
Published on
Modified on

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);
}
Walter Guevara is a software engineer, startup founder and currently teaches programming for a coding bootcamp. He is currently building things that don't yet exist.

Comments

No messages posted yet

Developer Poll

Q:

Stay up to date

Sign up for my FREE newsletter. Get informed of the latest happenings in the programming world.

Add a comment

Keep me up to date on the latest programming news
Add Comment

Stay up to date

Get informed of the latest happenings in the programming world.

No thanks