Can't remove all event listeners - javascript

I am trying to remove event listeners from some website but I don't succeed to do it.
This is the event listeners from the website:
There is a javascript script that creates these events with:
document.addEventListener('contextmenu', function (ev) {
ev.preventDefault();
}
)
I tried to remove it with:
document.removeEventListener('contextmenu', function (ev) {
ev.preventDefault();
})
I also tried with:
(getEventListeners(document)).contextmenu = null
But it didn't work, I think because I am using a new function which is not the same one.
Is there a way just to clear all the events ?
Referenced:
Can't remove event listener

You need to specify the function that was bound to removeEventListener
You can do this by creating a function and passing a reference to both addEventListener and removeEventListener.
// create a function
function onRightClick(ev) {
ev.preventDefault();
console.log('onRightClick')
}
// pass the function to both add and remove
document.addEventListener('contextmenu', onRightClick)
document.removeEventListener('contextmenu', onRightClick)
Here is a full example that will cache all the events to the element allowing you to remove specific events, all events for a type of all events.
It's also got a MutationObserver watching the DOM for changes, if an element get's removed so will the events attached to it.
const Events = (() => {
const cache = new Map
const observer = new MutationObserver(function(mutations) {
for (let mutation of mutations) {
if (mutation.type === 'childList') {
if (mutation.removedNodes.length) {
console.log('element removed from the dom, removing all events for the element')
mutation.removedNodes.forEach(x => Events.remove(x))
}
}
}
})
// watch the dom for the element being deleted
observer.observe(document.body, { childList: true })
return {
add(el, type, fn, capture = false) {
let cached = cache.get(el)
if (!cached) {
cached = {}
cache.set(el, cached)
}
if (!cached[type]) {
cached[type] = new Set
}
cached[type].add(fn)
el.addEventListener(type, fn, capture)
},
remove(el, type, fn) {
const cached = cache.get(el)
if (!cached) {
return false
}
// remove all events for an event type
if (type && !fn) {
cached[type].forEach(fn => {
el.removeEventListener(type, fn)
})
cached[type] = new Set
}
// remove a specific event
else if (type && fn) {
el.removeEventListener(type, fn)
// remove the event from the cache
cached[type].delete(fn)
}
// remove all events for the element
else {
for (key in cached) {
cached[key].forEach(fn => {
el.removeEventListener(key, fn)
})
}
cache.delete(el)
}
},
show(el, type) {
const cached = cache.get(el)
if (!cached) {
return false
}
if (type) {
return cached[type]
}
return cached
}
}
})()
function onRightClick() {}
Events.add(document, 'contextmenu', onRightClick)
Events.remove(document, 'contextmenu', onRightClick) // remove a specific event callback
Events.remove(document, 'contextmenu') // remove specific event types from an element
Events.remove(document) // remove all events from an element
const testElement = document.querySelector('#test_element')
Events.add(testElement, 'click', function deleteSelf(e) {
this.parentNode.removeChild(this)
})
<div id="test_element">
when you <strong>click me</strong> I will be deleted from the DOM which will fire the MutationObserver to remove all my events
</div>

You can try cloning the element to which you've added all the listeners and add it back to its parent. With cloning, you lose all the listeners attached to the element. Try this,
var element = document.getElementById('myElement'),
clone = el.cloneNode(true);
element.parentNode.replaceChild(clone, element);
However, this won't work on global event listeners, or simply, those set directly on document instead of an element as the document is the root of hierarchy (can't have parentNode)

To get rid of unknown event listeners you can clone the element and then move the original's content into the cloned one and then replace the original one with the clone.
If you don't care about the contained elements' event listeners, you can also deep clone the original with .clone(true) (or false, can't remember). Then you don't have to move the contents over.

Related

Remove event listener doesn't work as it should

I simply tried to addEventListener and removeEventListener to element, but it doesn't remove.
I suppose that the problem could be with parameters, but I used them to follow the DRY. So I could simply reuse it like nextSection.addEventListener('mouseover', showContent(event, nextSection)) and so on and so on so I do not need any if statements or stuff like that.
* EDIT *
I made some more examples of elements that I will be using. There’s a chance, that there will be event more. If I do not use parameter, there would be a lot more of functions. Also, there will be click instead of mouse events on mobile, so I need to remove them.
As I understand now, the problem is with return statement. If I use event instead of parameter and so event.target I get some weird bug.
const loginSection = document.querySelector('#js-login-section');
const searchSection = document.querySelector('#js-search-section');
const shoppingBagSection = document.querySelector('#js-shopping-bag-section');
const wishlistSection = document.querySelector('#js-wishlist-section');
function showContent(element) {
return () => {
const toggle = element.lastElementChild;
toggle.style.maxHeight = toggle.scrollHeight + 'px';
}
}
function hideContent(element) {
return () => {
const toggle = element.lastElementChild;
toggle.style.maxHeight = null;
}
}
/* Media queries - min width 992px */
loginSection.addEventListener('mouseover', showContent(loginSection));
loginSection.addEventListener('mouseout', hideContent(loginSection));
searchSection.addEventListener('mouseover', showContent(searchSection));
searchSection.addEventListener('mouseout', hideContent(searchSection));
shoppingBagSection.addEventListener('mouseover', showContent(shoppingBagSection));
shoppingBagSection.addEventListener('mouseout', hideContent(shoppingBagSection));
wishlistSection.addEventListener('mouseover', showContent(wishlistSection));
wishlistSection.addEventListener('mouseout', hideContent(wishlistSection));
/* Media queries - max width 992px */
loginSection.removeEventListener('mouseover', showContent(loginSection));
loginSection.removeEventListener('mouseout', hideContent(loginSection));
searchSection.removeEventListener('mouseover', showContent(searchSection));
searchSection.removeEventListener('mouseout', hideContent(searchSection));
shoppingBagSection.removeEventListener('mouseover', showContent(shoppingBagSection));
shoppingBagSection.removeEventListener('mouseout', hideContent(shoppingBagSection));
wishlistSection.removeEventListener('mouseover', showContent(wishlistSection));
wishlistSection.removeEventListener('mouseout', hideContent(wishlistSection));
Thank you in advance!
What is happening is that return () => {}; is returning a new function every time it's run. So every time you call one of your functions a new event handler is being created.
This means that the handler that is added is different to the one you're trying to remove.
To remedy this, I'd keep it simple:
const loginSection = document.querySelector('#js-login-section');
function showContent(e)
{
const toggle = e.currentTarget.lastElementChild;
toggle.style.maxHeight = toggle.scrollHeight + 'px';
}
function hideContent(e)
{
const toggle = e.currentTarget.lastElementChild;
toggle.style.maxHeight = null;
}
loginSection.addEventListener('mouseover', showContent);
loginSection.addEventListener('mouseout', hideContent);
loginSection.removeEventListener('mouseover', showContent);
loginSection.removeEventListener('mouseout', hideContent);
I'm not sure what you want to avoid repeating, so I can't advise on that, but I'm sure you'll figure it out.
const loginSection = document.querySelector('#js-login-section');
function showContent(event) {
var element = event.target;
return () => {
const toggle = element.lastElementChild;
toggle.style.maxHeight = toggle.scrollHeight + 'px';
}
}
function hideContent(event) {
var element = event.target;
return () => {
const toggle = element.lastElementChild;
toggle.style.maxHeight = null;
}
}
loginSection.addEventListener('mouseover', showContent);
loginSection.addEventListener('mouseout', hideContent);
loginSection.removeEventListener('mouseover', showContent);
loginSection.removeEventListener('mouseout', hideContent);
You must set in events method function without call. Element you can get from event event.target
In your code, I found the following errors,
param 'event' will be always undefined - the event should go as a parameter to inner function.
you don't need closure here - You can directly assign the function without creating an inner function and access the element with event.target or this
with your implementation, you should pass the same handler reference used in addEventListener to removeEventListener. So, you should store the handler in a variable and pass it to both addEventListener and removeEventListener
Solution:
if you don't know the handler name, you can use window.getEventListeners to do the magic,
window.getEventListeners returns a dictionary of events associated with the element.
function removeEventListener(el, eventName) {
if (!el) {
throw new Error('Invalid DOM reference passed');
}
const listeners = getEventListeners(el)[eventName] || [];
listeners.forEach(({
listener
}) => {
removeEventListener(eventName, listener);
});
}
function removeAllEventListener(el) {
if (!el) {
throw new Error('Invalid DOM reference passed');
}
const events = Object.entries(getEventListeners(el) || {});
events.forEach(([eventName, listeners]) => {
listeners.forEach(({
listener
}) => {
removeEventListener(eventName, listener);
});
});
}
// example
// remove mouseout event
removeEventListener(loginSection, 'mouseout');
// remove all event listeners
removeAllEventListener(loginSection);

Is there there an initial keypress event in JavaScript? [duplicate]

I want to have a onkeydown event fire a function only once. for that function to fire again, the user has to release the key and press/hold again.
I know its fairly simple but I'm new at JS. Also I prefer to avoid using jQuery or other libs.
One more thing, this should work for both ie and firefox.
I'm surprised it's not mentioned, there's also event.repeat:
document.addEventListener('keydown', (e) => {
if (e.repeat) return;
console.log(e.key);
});
This will only fire once per each keypress, since event.repeat turns true after holding the key down.
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key#keyboardevent_sequence
You could set a flag:
var fired = false;
element.onkeydown = function() {
if(!fired) {
fired = true;
// do something
}
};
element.onkeyup = function() {
fired = false;
};
Or unbind and rebind the event handler (might be better):
function keyHandler() {
this.onkeydown = null;
// do something
}
element.onkeydown = keyHandler;
element.onkeyup = function() {
this.onkeydown = keyHandler;
};
More information about "traditional" event handling.
You might also want to use addEventListener and attachEvent to bind the event handlers. For more information about that, have a look at quirksmode.org - Advanced event registration models.
There's a "once" parameter you can use
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
Eg:
element.addEventListener('keydown', function(event) {
doSomething()
}, {once: true});
It'll remove it as soon as it's been called.
Alternatively you can use removeEventListener if it's a named function
Here is a method that uses addEventListener and removeEventListener
var textBox = document.getElementById("textBox");
function oneKeyDown(){
$("body").append("<h1>KeyDown<h1>"); //just to show the keypress
textBox.removeEventListener('keydown', oneKeyDown, false);
}
function bindKeyDown(){
textBox.addEventListener('keydown', oneKeyDown, false);
}
textBox.addEventListener('keyup', bindKeyDown, false)
bindKeyDown();
Code example on jsfiddle.
One note, for IE you will need to use attachEvent, detachEvent.
Here you go:
test.onkeydown = function() {
if ( this.className === 'hold' ) { return false; }
this.className = 'hold';
// call your function here
};
test.onkeyup = function() {
this.className = '';
};
Live demo: http://jsfiddle.net/simevidas/xAReL/2/
JQuery's one will help you.
What it does is, bind the eventHandler to event, and when event occurs, it runs the eventHandler and unbinds it, so that its not fired at next event.
as stated in the other answers, there is no 'onkeyfirstdown' or similar event to listen for.
the best solution is to keep track of which keys are already down in a js-object:
var keysdown = {};
element.addEventListener('keydown', function(evt) {
if(!(evt.key in keysdown)) {
keysdown[evt.key] = true;
// key first pressed
}
});
element.addEventListener('keyup', function(evt) {
delete keysdown[evt.key];
});
this way, you will not be skipping 'keyfirstpressed' events if more than one key is held down.
(many of the other solutions posted here will only fire when no other keys are down).
Here is my solution that will only run the function you pass it when a key is FIRST pressed on the target (eg window or some input field). If the user wants to trigger a key again, they'll have to release it and press it again.
Vanilla JS
const onKeyPress = (func, target = window) => {
// persistent "store" to track what keys are being pressed
let pressed = {};
// whenever a keydown event is fired ontarget element
const onKeyDown = (event) => {
// if key isn't already pressed, run func
if (!pressed[event.which])
func(event);
// add key to store
pressed = { ...pressed, [event.which]: true };
};
// whenever a keyup event is fired on the window element
const onKeyUp = (event) => {
const { [event.which]: id, ...rest } = pressed;
// remove key from store
pressed = rest;
};
// add listeners
target.addEventListener('keydown', onKeyDown);
window.addEventListener('keyup', onKeyUp);
// return a function that can be called to remove listeners
return () => {
target.removeEventListener('keydown', onKeyDown);
window.removeEventListener('keyup', onKeyUp);
};
};
And then to use it:
const removeListener = onKeyPress((event) => console.log(event.which + ' key pressed'))
removeListener(); // when you want to remove listeners later
React and React Hooks
import { useState } from 'react';
import { useEffect } from 'react';
import { useCallback } from 'react';
export const useKeyPress = (func, target = window) => {
// persistent "store" to track what keys are being pressed
const [pressed, setPressed] = useState({});
// whenever a keydown event is fired ontarget element
const onKeyDown = useCallback(
(event) => {
// if key isn't already pressed, run func
if (!pressed[event.which])
func(event);
// add key to store
setPressed({ ...pressed, [event.which]: true });
},
[func, pressed]
);
// whenever a keyup event is fired on the window element
const onKeyUp = useCallback((event) => {
// remove key from store
const { [event.which]: id, ...rest } = pressed;
setPressed(rest);
}, [pressed]);
useEffect(() => {
// add listeners when component mounts/changes
target.addEventListener('keydown', onKeyDown);
window.addEventListener('keyup', onKeyUp);
// cleanup/remove listeners when component unmounts/changes
return () => {
target.removeEventListener('keydown', onKeyDown);
window.removeEventListener('keyup', onKeyUp);
};
}, [target, onKeyDown, onKeyUp]);
};
And then to use it:
import { useKeyPress } from 'wherever';
useKeyPress((event) => console.log(event.which + ' key pressed'))

Removing wrapped event handlers

I have a function which wraps a function around another one, then attaches it to a element.
function addCustomEvent(element, eventName, handler, useCapture) {
var wrappedHandler = function () {
// Do something here.
handler.call();
};
element.addEventListener(eventName, wrappedHandler, useCapture);
}
This works great and I also want to implement this function:
removeCustomEvent(element, eventName, handler, useCapture)
So I want to do something like this.
var clickHandler= function () { /* ... */ };
addCustomEvent(someElement, "click", clickHandler, false);
removeCustomEvent(someElement, "click", clickHandler, false);
There is a problem with this because I don't have a reference to the wrappedHandler in removeCustomEvent.
The only way I can think of now is to keep track of handlers and their corresponding wrappedHandlers in a dictionary so that I can find wrappedHandler from handler within the function, and remove it.
But I'm not fond of this approach because browser must have information about what handlers are attached, so creating a new dictionary seems redundant and waste of memory.
Is there a better, and much cleaner way?
Personally, I'd simply wrap the addCustomEvent and removeCustomEvent to a single module, and keep an object that tracks the bound handlers. You consider this "a waste of resources", but really, the impact of this approach would be negligible.
The upsides are: you have the beginning of a module that can easily be expanded on, to handle more complex event handlers (like simulating a tab event for mobile devices using the touchstart and touchend events).
An alternative approach would be to unbind the event handler internally, depending on the event object itself.
Then, you'll have to re-write your removeCustomEvent function to trigger a special event, that lets the bound handler know that you want to remove the event listener.
//in the wrappedHandler:
var wrappedHandler = function(e)
{
e = e || window.event;
if (e.synthetic === true)
{
e.preventDefault();
e.stopPropagation();
element.removeEventListener(eventName, wrappedHandler, useCapture);//<-- use closure vars
return e;//or return false.
}
//do normal event
handler.apply(this, [e]);//pass event object, and call handler in the same context!
};
var removeCustomEvent = function(event, node, capture)
{
var e, eClass,
doc = node.ownerDocument || (node.nodeType === (document.DOCUMENT_NODE || 9) ? node : document);
if (node.dispatchEvent)
{
if (event === 'click' || event.indexOf('mouse') >= 0)
eClass = 'MouseEvents';
else
eClass = 'HTMLEvents';
e = doc.createEvent(eClass);
e.initEvent(event, !(event === 'change'), true);
//THIS IS THE TRICK:
e.synthetic = true;
node.dispatchEvent(e, true);
return true;
}
if (node.fireEvent)
{
e = doc.createEventObject();
e.synthetic = true;
node.fireEvent('on' + event, e);
return true;
}
event = 'on' + event;
return node[event]();
};
here's a version of this code that is actually documented
I've set a synthetic property on the event object that will be passed to the event handler. the handler checks for this property, and if it's set to true, it will unbind the listener and return. This doesn't require you to keep DOM references and handlers in an object, but this is, I think you'll agree, quite a lot of work, too.
It also feels quite hacky, if you don't mind my saying so...
Compared to:
var binderModule = (function()
{
var module = {},
eventMap = {},
addEvent = function (elem, eventName, handler, capture)
{
var i, wrappedHandler;
if (!eventMap.hasOwnProperty(eventName))
eventMap[eventName] = [];
for (i=0;i<eventMap[eventName].length;++i)
{//look for elem reference
if (eventMap[eventName][i].node === elem)
break;
}
if (i>= eventMap[eventName].length)
{
i = eventMap[eventName].length;//set i to key
eventMap[eventName].push({
node: elem,
handlers: []//keep handlers here, in array for multiple handlers
});
}
wrappedHandler = function(e)
{
//stuff
return handler.apply(this, [e || window.event]);//pass arguments!
};
eventMap[eventNAme][i].handlers.push(wrappedHandler);
return elem.addEventListener(eventName, wrappedHandler, capture);
},
removeEvent(elem, eventName, capture)
{
var i, temp;
if (!eventMap.hasOwnProperty(eventName))
return;//no handlers bound, end here
for (i=0;i<eventMap[eventName].length;++i)
if (eventMap[eventName][i].node === elem)
break;
if (i < eventMap[eventName].length)
{//found element, remove listeners!
//get handlers
temp = eventMap[eventName][i].handlers;
//remove element + handlers from eventMap:
eventMap[evetnName][i] = undefined;
for (i=0;i<temp.length;++i)
elem.removeEventListener(eventName, temp[i], capture);
}
};
module.addCustomEvent = addEvent;
module.removeCustomEvent = removeEvent;
//or, perhaps better:
Object.defineProperty(module, 'addCustomEvent', {value: addEvent});//read-only
Object.defineProperty(module, 'removeCustomEvent', {value: removeEvent});
return module;
}());
Note that this is the basic setup to keep track of event handlers that are bound to particular DOM nodes, and how to mangage them. This code is not finished and is not tested. It probably contains typo's, syntax errors and some consistency issues. But this should be more than enough to get you started.

Remove All Event Listeners of Specific Type

I want to remove all event listeners of a specific type that were added using addEventListener(). All the resources I'm seeing are saying you need to do this:
elem.addEventListener('mousedown',specific_function);
elem.removeEventListener('mousedown',specific_function);
But I want to be able to clear it without knowing what it is currently, like this:
elem.addEventListener('mousedown',specific_function);
elem.removeEventListener('mousedown');
That is not possible without intercepting addEventListener calls and keep track of the listeners or use a library that allows such features unfortunately. It would have been if the listeners collection was accessible but the feature wasn't implemented.
The closest thing you can do is to remove all listeners by cloning the element, which will not clone the listeners collection.
Note: This will also remove listeners on element's children.
var el = document.getElementById('el-id'),
elClone = el.cloneNode(true);
el.parentNode.replaceChild(elClone, el);
If your only goal by removing the listeners is to stop them from running, you can add an event listener to the window capturing and canceling all events of the given type:
window.addEventListener(type, function(event) {
event.stopImmediatePropagation();
}, true);
Passing in true for the third parameter causes the event to be captured on the way down. Stopping propagation means that the event never reaches the listeners that are listening for it.
Keep in mind though that this has very limited use as you can't add new listeners for the given type (they will all be blocked). There are ways to get around this somewhat, e.g., by firing a new kind of event that only your listeners would know to listen for. Here is how you can do that:
window.addEventListener('click', function (event) {
// (note: not cross-browser)
var event2 = new CustomEvent('click2', {detail: {original: event}});
event.target.dispatchEvent(event2);
event.stopPropagation();
}, true);
element.addEventListener('click2', function(event) {
if (event.detail && event.detail.original) {
event = event.detail.original
}
// Do something with event
});
However, note that this may not work as well for fast events like mousemove, given that the re-dispatching of the event introduces a delay.
Better would be to just keep track of the listeners added in the first place, as outlined in Martin Wantke's answer, if you need to do this.
You must override EventTarget.prototype.addEventListener to build an trap function for logging all 'add listener' calls. Something like this:
var _listeners = [];
EventTarget.prototype.addEventListenerBase = EventTarget.prototype.addEventListener;
EventTarget.prototype.addEventListener = function(type, listener)
{
_listeners.push({target: this, type: type, listener: listener});
this.addEventListenerBase(type, listener);
};
Then you can build an EventTarget.prototype.removeEventListeners:
EventTarget.prototype.removeEventListeners = function(targetType)
{
for(var index = 0; index != _listeners.length; index++)
{
var item = _listeners[index];
var target = item.target;
var type = item.type;
var listener = item.listener;
if(target == this && type == targetType)
{
this.removeEventListener(type, listener);
}
}
}
In ES6 you can use a Symbol, to hide the original function and the list of all added listener directly in the instantiated object self.
(function()
{
let target = EventTarget.prototype;
let functionName = 'addEventListener';
let func = target[functionName];
let symbolHidden = Symbol('hidden');
function hidden(instance)
{
if(instance[symbolHidden] === undefined)
{
let area = {};
instance[symbolHidden] = area;
return area;
}
return instance[symbolHidden];
}
function listenersFrom(instance)
{
let area = hidden(instance);
if(!area.listeners) { area.listeners = []; }
return area.listeners;
}
target[functionName] = function(type, listener)
{
let listeners = listenersFrom(this);
listeners.push({ type, listener });
func.apply(this, [type, listener]);
};
target['removeEventListeners'] = function(targetType)
{
let self = this;
let listeners = listenersFrom(this);
let removed = [];
listeners.forEach(item =>
{
let type = item.type;
let listener = item.listener;
if(type == targetType)
{
self.removeEventListener(type, listener);
}
});
};
})();
You can test this code with this little snipper:
document.addEventListener("DOMContentLoaded", event => { console.log('event 1'); });
document.addEventListener("DOMContentLoaded", event => { console.log('event 2'); });
document.addEventListener("click", event => { console.log('click event'); });
document.dispatchEvent(new Event('DOMContentLoaded'));
document.removeEventListeners('DOMContentLoaded');
document.dispatchEvent(new Event('DOMContentLoaded'));
// click event still works, just do a click in the browser
Remove all listeners on a global event
element.onmousedown = null;
now you can go back to adding event listeners via
element.addEventListener('mousedown', handler, ...);
This solution only works on "Global" events. Custom events won't work. Here's a list of all global events: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers
I know this is old, but I had a similar issue with no real answers, where I wanted to remove all keydown event listeners from the document. Instead of removing them, I override the addEventListener to ignore them before they were even added, similar to Toms answer above, by adding this before any other scripts are loaded:
<script type="text/javascript">
var current = document.addEventListener;
document.addEventListener = function (type, listener) {
if(type =="keydown")
{
//do nothing
}
else
{
var args = [];
args[0] = type;
args[1] = listener;
current.apply(this, args);
}
};
</script>
A modern way to remove event listeners without referencing the original function is to use AbortController. A caveat being that you can only abort the listeners that you added yourself.
const buttonOne = document.querySelector('#button-one');
const buttonTwo = document.querySelector('#button-two');
const abortController = new AbortController();
// Add multiple click event listeners to button one
buttonOne.addEventListener(
'click',
() => alert('First'),
{ signal: abortController.signal }
);
buttonOne.addEventListener(
'click',
() => alert('Second'),
{ signal: abortController.signal }
);
// Add listener to remove first button's listeners
buttonTwo.addEventListener(
'click',
() => abortController.abort()
);
<p>The first button will fire two alert dialogs when clicked. Click the second button to remove those listeners from the first button.</p>
<button type="button" id="button-one">Click for alerts</button>
<button type="button" id="button-two">Remove listeners</button>
Remove all listeners in element by one js line:
element.parentNode.innerHTML += '';
You cant remove a single event, but all? at once? just do
document.body.innerHTML = document.body.innerHTML
In the extreme case of not knowing which callback is attached to a window listener, an handler can be wrapper around window addEventListener and a variable can store ever listeners to properly remove each one of those through a removeAllEventListener('scroll') for example.
var listeners = {};
var originalEventListener = window.addEventListener;
window.addEventListener = function(type, fn, options) {
if (!listeners[type])
listeners[type] = [];
listeners[type].push(fn);
return originalEventListener(type, fn, options);
}
var removeAllEventListener = function(type) {
if (!listeners[type] || !listeners[type].length)
return;
for (let i = 0; i < listeners[type].length; i++)
window.removeEventListener(type, listeners[type][i]);
}
So this function gets rid of most of a specified listener type on an element:
function removeListenersFromElement(element, listenerType){
const listeners = getEventListeners(element)[listenerType];
let l = listeners.length;
for(let i = l-1; i >=0; i--){
removeEventListener(listenerType, listeners[i].listener);
}
}
There have been a few rare exceptions where one can't be removed for some reason.
You could alternatively overwrite the 'yourElement.addEventListener()' method and use the '.apply()' method to execute the listener like normal, but intercepting the function in the process. Like:
<script type="text/javascript">
var args = [];
var orginalAddEvent = yourElement.addEventListener;
yourElement.addEventListener = function() {
//console.log(arguments);
args[args.length] = arguments[0];
args[args.length] = arguments[1];
orginalAddEvent.apply(this, arguments);
};
function removeListeners() {
for(var n=0;n<args.length;n+=2) {
yourElement.removeEventListener(args[n], args[n+1]);
}
}
removeListeners();
</script>
This script must be run on page load or it might not intercept all event listeners.
Make sure to remove the 'removeListeners()' call before using.
var events = [event_1, event_2,event_3] // your events
//make a for loop of your events and remove them all in a single instance
for (let i in events){
canvas_1.removeEventListener("mousedown", events[i], false)
}

Jquery not deep copying from event handler

I have an event handler set up using plain javascript like this:
myElement.addEventListener('drop', handleDrop, false);
Then, inside handle drop I try to do this:
var myContainer = $(this.parentNode);
myContainer.after(myContainer.clone(true, true));
However, it appears that the event is not being carried over to the cloned element. Is this happening because I am not binding the event with jQuery also?
I tried to test this by binding the event with jQuery instead, but that doesn't support the dataTransfer object so it broke other code.
One solution is to write your own wrapper for addEventListener that remembers the listeners which were added, so they can be "replayed":
// set an event handler after memoizing it
function myAddEventListener(element, type, listener, useCapture) {
// store listeners as an array under element.listeners
if (!element.listeners) { element.listeners=[]; }
// each element of the array is an array of arguments to addEventListener
element.listeners[element.listeners.length] =
Array.prototype.slice.call(arguments,1);
// apply listener to element itself
element.addEventListener (type, listener, useCapture);
}
// copy a list of event handlers from one element to another
function copyEventListeners (from_element, to_element) {
var i;
if (from_element.listeners) {
for (i=0; i<from_element.listeners.length; i++) {
Element.addEventListener.apply (to_element, from_element.listeners[i]);
}
}
}
Then:
function clone_with_listeners (element) {
var cloned_element = element.cloneNode();
copyEventListeners (element, cloned_element);
return cloned_element;
}
If you have no religious convictions preventing you from overwriting the original method on the Element object:
var orgAddEventListener = Element.addEventListener;
// our version of addEventListener
Element.addEventListener = function (type, listener, useCapture) {
// store listeners as an array under element.listeners
if (!this.listeners) { this.listeners=[]; }
// each element of the array is an array of arguments to addEventListener
this.listeners[element.listeners.length] =
Array.prototype.slice.call (arguments,0);
// apply listener to element itself
orgAddEventListener.call (element, type, listener, useCapture);
};
// copy a list of event handlers from this element to another
Element.copyEventListeners = function (to_element) {
var i;
if (from_element.listeners) {
for (i=0; i<this.listeners.length; i++) {
Element.addEventListener.apply (to_element, this.listeners[i]);
}
}
};
and then:
Element.cloneNode = function () {
var cloned_element = this.cloneNode();
this.copyEventListeners (cloned_element);
return cloned_element;
};

Categories