Home >Web Front-end >JS Tutorial >How Can I Remove Event Listeners from DOM Objects in JavaScript?

How Can I Remove Event Listeners from DOM Objects in JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-10-25 05:46:02367browse

How Can I Remove Event Listeners from DOM Objects in JavaScript?

Removing Event Listeners from DOM Objects

Removing All Event Handlers

To remove all event handlers from an object, you can clone the element and replace it with the clone:

<code class="javascript">var clone = element.cloneNode(true);</code>

This method preserves attributes and children, but not changes to DOM properties.

Removing Event Handlers with Anonymous Functions

You can remove event handlers with anonymous functions by storing a reference to the returned function and creating a separate function to remove all events:

<code class="javascript">var _eventHandlers = {};

const addListener = (node, event, handler, capture = false) => {
  if (!(event in _eventHandlers)) {
    _eventHandlers[event] = []
  }
  _eventHandlers[event].push({ node: node, handler: handler, capture: capture })
  node.addEventListener(event, handler, capture)
}

const removeAllListeners = (targetNode, event) => {
  _eventHandlers[event]
    .filter(({ node }) => node === targetNode)
    .forEach(({ node, handler, capture }) => node.removeEventListener(event, handler, capture))

  _eventHandlers[event] = _eventHandlers[event].filter(
    ({ node }) => node !== targetNode,
  )
}</code>

This allows you to add and remove event listeners using:

<code class="javascript">addListener(div, 'click', eventReturner(), false)
removeAllListeners(div, 'click')</code>

Direct Event Handling

If you use an anonymous function to handle events, you can simply add and remove it directly:

<code class="javascript">function handler() {
  dosomething();
}

div.addEventListener('click',handler,false);</code>

The above is the detailed content of How Can I Remove Event Listeners from DOM Objects in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:EDD with event emittersNext article:EDD with event emitters