removeEventListner after event has been triggered - javascript

I have a script that adds a click event to a div to add a new element. Then the function creates and adds the element, and is then supposed to remove the click even from the Div so no farther elements can be added. I understand why the removeEventListener isn't working, but I don't know how to fix it. Here are the lines of code that are giving me the problem:
function enable_add(tag, type){return function(e){add_element(e, tag, type);};} //Function call for adding new elements
document.getElementById("body_visual_editor").addEventListener("click", enable_add(tag, type));
document.getElementById("body_visual_editor").removeEventListener("click", enable_add());
Fire bug says that function(e) is assigned as the event, not enable_add, so the remove event does not find the right event. How do I write these three lines so they all work right?
No javascript libraries please.
Update: So i got the orignal isue sovled by rewriting it like this:
var handler;
function enable_add(tag, type) //Function call for adding new elements
{
handler= function handler(e){add_element(e, tag, type);};
return handler
}
document.getElementById("body_visual_editor").addEventListener("click", enable_add(tag, type));
document.getElementById("body_visual_editor").removeEventListener("click", handler);
But now it creates a element on the add_element call for etting the handler, and one on click. How do I fix that?

Here's the problem:
You've got a partially applied function, that you're passing directly into addEventListener.
removeEventListener only works on the exact same function instance as what was passed to addEventListener.
function makeFunction () {
return function () { };
}
var func1 = makeFunction();
var func2 = makeFunction();
func1 === func2; // false
So your solution is to cache the created function as a reference, which you then pass into addEventListener, remember it, and pass it into removeEventListener.
var myHandler = makeFunction();
el.addEventListener("click", myHandler);
el.removeEventListener("click", myHandler);
...of course, you probably don't intend to remove it, instantly.
Which means that you need to get more creative.
function handleEventOnce (evt, el, action) {
function doSomething (e) {
action(e);
el.removeEventListener(evt, doSomething);
}
el.addEventListener(evt, doSomething);
}
handleEventOnce("click", button, somePartialFunction(a, b));

Edit, Updated
Try naming anonymous function , utilizing Function.prototype.call() , Function.prototype.bind() , arguments , to pass this , event objects
var namedHandler;
function enable_add(tag, type) {
namedHandler = function namedHandler() {
add_element.call(this, arguments[arguments.length - 1], tag, type)
}.bind(this, tag, type);
return namedHandler
}
function add_element(e, tag, type) {
var el = document.createElement(tag);
el.setAttribute("type", type);
document.body.appendChild(el);
this.removeEventListener("click", namedHandler)
}
var elem = document.getElementById("body_visusal_editor");
elem.addEventListener("click", enable_add.call(elem, "input", "text"))
<div id="body_visusal_editor">click to add one element</div>
jsfiddle http://jsfiddle.net/oe71yfn8/

Calling the function again will create a new function, so that won't work. You would have to store the EventListener as a variable in order to pass it to removeEventListener.

Related

How to delete listener with anonymous function? [duplicate]

I have an object that has methods in it. These methods are put into the object inside an anonymous function. It looks like this:
var t = {};
window.document.addEventListener("keydown", function(e) {
t.scroll = function(x, y) {
window.scrollBy(x, y);
};
t.scrollTo = function(x, y) {
window.scrollTo(x, y);
};
});
(there is a lot more code, but this is enough to show the problem)
Now I want to stop the event listener in some cases. Therefore I am trying to do a removeEventListener but I can't figure out how to do this. I have read in other questions that it is not possible to call removeEventListener on anonymous functions, but is this also the case in this situation?
I have a method in t created inside the anonymous function and therefore I thought it was possible. Looks like this:
t.disable = function() {
window.document.removeEventListener("keydown", this, false);
}
Why can't I do this?
Is there any other (good) way to do this?
Bonus info; this only has to work in Safari, hence the missing IE support.
You can name the function passed and use the name in the removeEventListener. as in:
button.addEventListener('click', function eventHandler() {
///this will execute only once
alert('only once!');
this.removeEventListener('click', eventHandler);
});
EDIT:
This will not work if you are working in strict mode ("use strict";)
EDIT 2:
arguments.callee is now deprecated (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee)
I believe that is the point of an anonymous function, it lacks a name or a way to reference it.
If I were you I would just create a named function, or put it in a variable so you have a reference to it.
var t = {};
var handler = function(e) {
t.scroll = function(x, y) {
window.scrollBy(x, y);
};
t.scrollTo = function(x, y) {
window.scrollTo(x, y);
};
};
window.document.addEventListener("keydown", handler);
You can then remove it by
window.document.removeEventListener("keydown", handler);
A version of Otto Nascarella's solution that works in strict mode is:
button.addEventListener('click', function handler() {
///this will execute only once
alert('only once!');
this.removeEventListener('click', handler);
});
in modern browsers you can do the following...
button.addEventListener( 'click', () => {
alert( 'only once!' );
}, { once: true } );
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Parameters
window.document.removeEventListener("keydown", getEventListeners(window.document.keydown[0].listener));
May be several anonymous functions, keydown1
Warning: only works in Chrome Dev Tools & cannot be used in code: link
There's a new way to do this that is supported by the latest versions of most popular browsers with the exception of Safari.
Check caniuse for updated support.
Update: Now also supported by Sefari (version 15^).
We can add an option to addEventListner called signal and assign a signal from an AbortController on which you can later call the abort() method.
Here is an example.
We create an AbortController:
const controller = new AbortController();
Then we create the eventListner and pass in the option signal:
document.addEventListener('scroll',()=>{
// do something
},{signal: controller.signal})
And then to remove the eventListner at a later time, we call:
controller.abort()
This is not ideal as it removes all, but might work for your needs:
z = document.querySelector('video');
z.parentNode.replaceChild(z.cloneNode(1), z);
Cloning a node copies all of its attributes and their values, including
intrinsic (in–line) listeners. It does not copy event listeners added using
addEventListener()
Node.cloneNode()
A not so anonymous option
element.funky = function() {
console.log("Click!");
};
element.funky.type = "click";
element.funky.capt = false;
element.addEventListener(element.funky.type, element.funky, element.funky.capt);
// blah blah blah
element.removeEventListener(element.funky.type, element.funky, element.funky.capt);
Since receiving feedback from Andy (quite right, but as with many examples, I wished to show a contextual expansion of the idea), here's a less complicated exposition:
<script id="konami" type="text/javascript" async>
var konami = {
ptrn: "38,38,40,40,37,39,37,39,66,65",
kl: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
};
document.body.addEventListener( "keyup", function knm ( evt ) {
konami.kl = konami.kl.slice( -9 );
konami.kl.push( evt.keyCode );
if ( konami.ptrn === konami.kl.join() ) {
evt.target.removeEventListener( "keyup", knm, false );
/* Although at this point we wish to remove a listener
we could easily have had multiple "keyup" listeners
each triggering different functions, so we MUST
say which function we no longer wish to trigger
rather than which listener we wish to remove.
Normal scoping will apply to where we can mention this function
and thus, where we can remove the listener set to trigger it. */
document.body.classList.add( "konami" );
}
}, false );
document.body.removeChild( document.getElementById( "konami" ) );
</script>
This allows an effectively anonymous function structure, avoids the use of the practically deprecated callee, and allows easy removal.
Incidentally: The removal of the script element immediately after setting the listener is a cute trick for hiding code one would prefer wasn't starkly obvious to prying eyes (would spoil the surprise ;-)
So the method (more simply) is:
element.addEventListener( action, function name () {
doSomething();
element.removeEventListener( action, name, capture );
}, capture );
To give a more up-to-date approach to this:
//one-time fire
element.addEventListener('mousedown', {
handleEvent: function (evt) {
element.removeEventListener(evt.type, this, false);
}
}, false);
JavaScript: addEventListener
method registers the specified listener on the EventTarget(Element|document|Window) it's called on.
EventTarget.addEventListener(event_type, handler_function, Bubbling|Capturing);
Mouse, Keyboard events Example test in WebConsole:
var keyboard = function(e) {
console.log('Key_Down Code : ' + e.keyCode);
};
var mouseSimple = function(e) {
var element = e.srcElement || e.target;
var tagName = element.tagName || element.relatedTarget;
console.log('Mouse Over TagName : ' + tagName);
};
var mouseComplex = function(e) {
console.log('Mouse Click Code : ' + e.button);
}
window.document.addEventListener('keydown', keyboard, false);
window.document.addEventListener('mouseover', mouseSimple, false);
window.document.addEventListener('click', mouseComplex, false);
removeEventListener
method removes the event listener previously registered with EventTarget.addEventListener().
window.document.removeEventListener('keydown', keyboard, false);
window.document.removeEventListener('mouseover', mouseSimple, false);
window.document.removeEventListener('click', mouseComplex, false);
caniuse
I have stumbled across the same problem and this was the best solution I could get:
/*Adding the event listener (the 'mousemove' event, in this specific case)*/
element.onmousemove = function(event) {
/*do your stuff*/
};
/*Removing the event listener*/
element.onmousemove = null;
Please keep in mind I have only tested this for the window element and for the 'mousemove' event, so there could be some problems with this approach.
Possibly not the best solution in terms of what you are asking. I have still not determined an efficient method for removing anonymous function declared inline with the event listener invocation.
I personally use a variable to store the <target> and declare the function outside of the event listener invocation eg:
const target = document.querySelector('<identifier>');
function myFunc(event) {
function code;
}
target.addEventListener('click', myFunc);
Then to remove the listener:
target.removeEventListener('click', myFunc);
Not the top recommendation you will receive but to remove anonymous functions the only solution I have found useful is to remove then replace the HTML element. I am sure there must be a better vanilla JS method but I haven't seen it yet.
I know this is a fairly old thread, but thought I might put in my two cents for those who find it useful.
The script (apologies about the uncreative method names):
window.Listener = {
_Active: [],
remove: function(attached, on, callback, capture){
for(var i = 0; i < this._Active.length; i++){
var current = this._Active[i];
if(current[0] === attached && current[1] === on && current[2] === callback){
attached.removeEventListener(on, callback, (capture || false));
return this._Active.splice(i, 1);
}
}
}, removeAtIndex(i){
if(this._Active[i]){
var remove = this._Active[i];
var attached = remove[0], on = remove[1], callback = remove[2];
attached.removeEventListener(on, callback, false);
return this._Active.splice(i, 1);
}
}, purge: function(){
for(var i = 0; i < this._Active.length; i++){
var current = this._Active[i];
current[0].removeEventListener(current[1], current[2]);
this._Active.splice(i, 1);
}
}, declare: function(attached, on, callback, capture){
attached.addEventListener(on, callback, (capture || false));
if(this._Active.push([attached, on, callback])){
return this._Active.length - 1;
}
}
};
And you can use it like so:
// declare a new onclick listener attached to the document
var clickListener = Listener.declare(document, "click" function(e){
// on click, remove the listener and log the clicked element
console.log(e.target);
Listener.removeAtIndex(clickListener);
});
// completely remove all active listeners
// (at least, ones declared via the Listener object)
Listener.purge();
// works exactly like removeEventListener
Listener.remove(element, on, callback);
I just experienced similiar problem with copy-protection wordpress plugin. The code was:
function disableSelection(target){
if (typeof target.onselectstart!="undefined") //For IE
target.onselectstart=function(){return false}
else if (typeof target.style.MozUserSelect!="undefined") //For Firefox
target.style.MozUserSelect="none"
else //All other route (For Opera)
target.onmousedown=function(){return false}
target.style.cursor = "default"
}
And then it was initiated by loosely put
<script type="text/javascript">disableSelection(document.body)</script>.
I came around this simply by attaching other annonymous function to this event:
document.body.onselectstart = function() { return true; };
Set anonymous listener:
document.getElementById('ID').addEventListener('click', () => { alert('Hi'); });
Remove anonymous listener:
document.getElementById('ID').removeEventListener('click',getEventListeners(document.getElementById('ID')).click[0].listener)
Using the AbortController, neat and clean
Attaching EventListener
const el = document.getElementById('ID')
const controller = new AbortController;
el.addEventListener('click',() => {
console.log("Clicked")
},{signal: controller.signal})
when you want to remove the event listener
controller.abort()
Another alternative workaround to achieve this is adding an empty event handler and preventing event propagation.
Let's assume you need to remove mouseleave event handler from an element which has #specific-div id, that is added with an anonymous function, and you can't use removeEventListener() since you don't have a function name.
You can add another event handler to that element and use event.stopImmediatePropagation(), for being sure this event handler works before existing ones you should pass the third parameter (useCapture) as true.
The final code should look like the below:
document.getElementById("specific-div")
.addEventListener("mouseleave", function(event) {
event.stopImmediatePropagation()
}, true);
This could help for some specific cases that you can't prefer cloneNode() method.
window.document.onkeydown = function(){};

why removeEventListener is not working

Could someone help to check why the removeHandler is not working? And how to make it work?
Thanks.
<body>
<button onclick="removeHandler()" id="myBtn">remove</button>
<p id="demo">hello</p>
<script>
document.getElementById("demo").addEventListener("click", myFunction("random: "));
function myFunction(t) {
var x = function(){
document.getElementById("demo").innerHTML = t+Math.random();
};
return x;
}
function removeHandler() {
document.getElementById("demo").removeEventListener("click", myFunction("random: "));
}
</script>
</body>
Becasue myFunction returns a new function for each call. Each time you call myFunction, it creates (define) a new function, and return it.
function myFunction() {
return function() {};
}
var f1 = myFunction();
var f2 = myFunction();
console.log(f1 === f2);
FIX:
You have to store the return value of myFunction into a variable, and then pass that variable to both addEventListener and removeEventListener:
var f = myFunction("random: ");
document.getElementById("demo").addEventListener("click", f, false);
// ...
document.getElementById("demo").removeEventListener("click", f);
If you are using React functional component, just be sure to wrap your function inside useCallback hooks, or the function will not be the same after re-rendering. Below is an example that I put the event listener inside useEffect in order to demonstrate re-rendering.
Also make sure that is you are calling another function inside useCallback function, that function should also be wrapped within useCallback to prevent the function from re-initializing.
If these "other function" has dependent on other state, this might cause removeEventListener not working cause the function is re-initialized, which the reference of that function is not the same.
const test = useCallback(() => {...}, [])
useEffect(() => {
if (isTest) document.addEventListener('mousemove', test, true)
else document.removeEventListener('mousemove', test, true)
}, [isTest])
JavaScript is very particular when it comes to removing event listeners. You can only remove the same event listener that you have previously added. It also needs to match whether it’s bubbling.
Among other things, that means that you cannot remove an anonymous event listener since you have no way of identifying it.
In your case, you’re compounding the problem by actually attempting to remove a newly created event listener.
The only way to remove an event listener is to ensure that it has a name. In your case, it would be as follows:
var random=myFunction("random: ");
document.getElementById("demo").addEventListener("click", random,false);
function myFunction(t) {
var x = function(){
document.getElementById("demo").innerHTML = t+Math.random();
};
return x;
}
function removeHandler() {
document.getElementById("demo").removeEventListener("click", random,false);
}
Note:
There is a variable name (random in this case) to identify the event listener function
I have also added false as a third parameter to ensure that the remove matches the add.
It seems every time you click on demo function call return new function so that its not behaving as expected.
try running Example
<body>
<p id="demo">Hello</p>
<button onclick="removeHandler()" id="myBtn">Try it</button>
<p><strong>Note:</strong> The addEventListener() and removeEventListener() methods are not supported in Internet Explorer 8 and earlier versions.</p>
<script>
document.getElementById("demo").addEventListener("click", myFunction);
function myFunction() {
document.getElementById("demo").innerHTML = Math.random();
}
function removeHandler() {
document.getElementById("demo").removeEventListener("click", myFunction);
}
</script>

Calling a function before any click event handler

Hi I want to call a function every time before any click event handler method.
I know, inside the click handler method I can call my function first, but this quite cumbersome as I have to do this at so many place as well as I have to keep in mind the same for any future click events.
You can set a capture event handler on the document object (or any common parent) and it will be called first before the event handler on the individual object. capture is the third argument to .addEventListener() which is normally optional and defaults to false, but if you pass true on a parent, then the event handler will be called first.
Here's an example:
document.addEventListener("click", function() {
log("document capture click");
}, true);
document.getElementById("target").addEventListener("click", function() {
log("element click");
}, false);
function log(x) {
var div = document.createElement("div");
div.innerHTML = x;
document.body.appendChild(div);
}
<div id="target">Some text to click on</div>
Here's a related question that helps to understand the capture flag: Unable to understand useCapture attribute in addEventListener
I see two solutions here.
First is to use onmousedown that is fired before click event
document.querySelector('.selector').addEventListener('mousedown', function(){
console.log('mousedown');
}
document.querySelector('.selector').addEventListener('click', function(){
console.log('click');
}
Other way is to use compose that will create new reusable function for you (npm i lodash.compose).
var compose = require(lodash.compose);
var firstFunc = function(e){
console.log('first');
return e; //if you want to use it in second function
};
var secondFunc = function(e) {
console.log('second');
};
document.querySelector('.selector').addEventListener('click', compose(secondFunc, firstFunc));
Or you could save new func in variable;
var logFirstThanSecondOnClick = compose(secondFunc, firstFunc);
document.querySelector('.selector').addEventListener('click', logFirstThanSecondOnClick);
Simply compose do next
function compose(f, g) {
return function(x) {
return f(g(x));
}
}
But lodash one is more complex inside.
Here is some math theory about function composition, if you are interested in https://en.wikipedia.org/wiki/Function_composition

How to detect when an .html() function is called in jQuery?

The problem is simple. I have a massive javascript application. And there are lot of times in the app where I use code which looks something like this -
$('#treat').html(new_data);
....
....
$('#cool').html(some_html_data);
....
....
$('#not_cool').html(ajax_data);
So what I want to do is, everytime this html() function is called I want to execute a set of functions.
function do_these_things_every_time_data_is_loaded_into_a_div()
{
$('select').customSelect();
$('input').changeStyle();
etc.
}
How do I do this? Thank you.
You can use the custom event handlers for that:
$('#treat').html(new_data);
// Trigger the custom event after html change
$('#treat').trigger('custom');
// Custom event handler
$('#treat').on('custom', function( event) {
// do_these_things_every_time_data_is_loaded_into_a_div
alert('Html had changed!');
});
UPDATE
Based on answer over here and with some modifications you can do this:
// create a reference to the old `.html()` function
$.fn.htmlOriginal = $.fn.html;
// redefine the `.html()` function to accept a callback
$.fn.html = function (html, callback) {
// run the old `.html()` function with the first parameter
this.htmlOriginal(html);
// run the callback (if it is defined)
if (typeof callback == "function") {
callback();
}
}
$("#treat").html(new_data, function () {
do_these_things_every_time_data_is_loaded_into_a_div();
});
$("#cool").html(new_data, function () {
do_these_things_every_time_data_is_loaded_into_a_div();
});
Easily maintainable and less code as per your requirements.
You can overwrite the jQuery.fn.html() method, as described in Override jQuery functions
For example, use this:
var oHtml = jQuery.fn.html;
jQuery.fn.html = function(value) {
if(typeof value !== "undefined")
{
jQuery('select').customSelect();
jQuery('input').changeStyle();
}
// Now go back to jQuery's original html()
return oHtml.apply(this, value);
};
When html() is called it usually make the DOM object changes, so you can look for DOM change event handler, it is called whenever your HTML of main page change. I found
Is there a JavaScript/jQuery DOM change listener?
if this help your cause.
You can replace the html function with your own function and then call the function html:
$.fn.html = (function(oldHtml) {
var _oldHtml = oldHtml;
return function(param) {
// your code
alert(param);
return _oldHtml.apply(this, [param]);
};
})($.fn.html);
I have a little script for you. Insert that into your javascript:
//#Author Karl-André Gagnon
$.hook = function(){
$.each(arguments, function(){
var fn = this
if(!$.fn['hooked'+fn]){
$.fn['hooked'+fn] = $.fn[fn];
$.fn[fn] = function(){
var r = $.fn['hooked'+fn].apply(this, arguments);
$(this).trigger(fn, arguments);
return r
}
}
})
}
This allow you to "hook" jQuery function and trigger an event when you call it.
Here how you use it, you first bind the function you want to trigger. In your case, it will be .html():
$.hook('html');
Then you add an event listener with .on. It there is no dynamicly added element, you can use direct binding, else, delegated evets work :
$(document).on('html', '#threat, #cool, #not_cool',function(){
alert('B');
})
The function will launch everytime #threat, #cool or #not_cool are calling .html.
The $.hook plugin is not fully texted, some bug may be here but for your HTML, it work.
Example : http://jsfiddle.net/5svVQ/

What's the easiest way i can pass an element as a first argument to event handlers in JavaScript?

I know that having the value of this being changed to the element receiving the event in event handling functions is pretty useful. However, I'd like to make my functions always be called in my application context, and not in an element context. This way, I can use them as event handlers and in other ways such as in setTimeout calls.
So, code like this:
window.app = (function () {
var that = {
millerTime: function () {},
changeEl: function (el) {
el = el || this;
// rest of code...
that.millerTime();
}
};
return that;
}());
could just be like this:
window.app = (function () {
return {
millerTime: function () {},
changeEl: function (el) {
// rest of code...
this.millerTime();
}
};
}());
The first way just looks confusing to me. Is there a good easy way to pass the element receiving the event as the first argument (preferably a jQuery-wrapped element) to my event handling function and call within the context of app? Let's say I bind a bunch of event handlers using jQuery. I don't want to have to include anonymous functions all the time:
$('body').on('click', function (event) {
app.changeEl.call(app, $(this), event); // would be nice to get event too
});
I need a single function that will take care of this all for me. At this point I feel like there's no getting around passing an anonymous function, but I just want to see if someone might have a solution.
My attempt at it:
function overrideContext (event, fn) {
if (!(this instanceof HTMLElement) ||
typeof event === 'undefined'
) {
return overrideContext;
}
// at this point we know jQuery called this function // ??
var el = $(this);
fn.call(app, el, event);
}
$('body').on('click', overrideContext(undefined, app.changeEl));
Using Function.prototype.bind (which I am new to), I still can't get the element:
window.app = (function () {
return {
millerTime: function () {},
changeEl: function (el) {
// rest of code...
console.log(this); // app
this.millerTime();
}
};
}());
function overrideContext (evt, fn) {
var el = $(this); // $(Window)
console.log(arguments); // [undefined, app.changeEl, p.Event]
fn.call(app, el, event);
}
$('body').on('click', overrideContext.bind(null, undefined, app.changeEl));
Using $('body').on('click', overrideContext.bind(app.changeEl)); instead, this points to my app.changeEl function and my arguments length is 1 and contains only p.Event. I still can't get the element in either instance.
Defining a function like this should give you what you want:
function wrap(func) {
// Return the function which is passed to `on()`, which does the hard work.
return function () {
// This gets called when the event is fired. Call the handler
// specified, with it's context set to `window.app`, and pass
// the jQuery element (`$(this)`) as it's first parameter.
func.call(window.app, $(this) /*, other parameters (e?)*/);
}
}
You'd then use it like so;
$('body').on('click', wrap(app.changeEl));
For more info, see Function.call()
Additionally, I'd like to recommend against this approach. Well versed JavaScript programmers expect the context to change in timeouts and event handlers. Taking this fundamental away from them is like me dropping you in the Sahara with no compass.

Categories

Resources