Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
html
community creator

How to remove a DOM event listener using Javascript

Osinachi Chukwujama

To remove a DOM event listener:

  1. Call DOMElement.removeEventListener(event, originalFunction), where DOMElement is the element with the listener.
  2. The originalFunction parameter should be the same function as the one passed to addEventListener.

Example

The code block below contains an HTML template with a form, an output section, and a button that disables the form. The form’s default reload-on-submit behavior was removed using event.preventDefault().

Once the form is submitted, the input string is reversed and displayed in the output section.

The displayReverseString function in the Javascript tab, line 6, was added as a submit event handler to the form. This submit event handler is removed by calling,

form.removeEventListener('submit', displayReverseString)

It’s important that the same function is passed, otherwise, the removeEventListener call won’t give the desired result.

When the Disable form button is clicked, the form resumes its normal behavior of refreshing the page.

RELATED TAGS

javascript
html
community creator
RELATED COURSES

View all Courses

Keep Exploring