Home > Web Front-end > JS Tutorial > body text

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

Barbara Streisand
Release: 2024-10-25 05:46:02
Original
316 people have browsed it

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>
Copy after login

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>
Copy after login

This allows you to add and remove event listeners using:

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

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!