Skip to content Skip to sidebar Skip to footer

Removing Event Listeners On Automatically Created Multiple Elements

I'm trying to remove event listeners from elements after they've been clicked on and although I seem to have a working solution, it's not ideal and I'm not sure why it works differ

Solution 1:

you are right, you don't need an array, just hold every listener in a variable, than pass eventlistener in your remove() function,

var ctnr = document.getElementById('ctnr');

functionremoveDiv(d, ev) {
    alert('testing');
    d.removeEventListener('click', ev, false);
}

functionaddDiv() {
    var div = document.createElement('div');
    div.innerHTML = 'test';
    ctnr.appendChild(div);
    div.addEventListener('click', (function(d) {
        var myfunc;
        return myfunc = function() {
            removeDiv(d, myfunc);
        }
    })(div), false);
}


addDiv();
addDiv();
addDiv();

document.getElementById('btn').addEventListener('click', function() {
    alert(listeners);
}, false);​​

updated jsfiddle page

Solution 2:

You have to save each and every listener if they are unequal, so you need a relation between listener and element. Since an element is represented by an object (DOM: document object model) you can add custom properties to them (although it's not recommended: Can I add arbitrary properties to DOM objects?) (demo):

var ctnr = document.getElementById('ctnr');

functionremoveDiv (d) {
    alert('testing');
    d.removeEventListener('click', d.custom_Listener , false);
}

functionaddDiv () {
    var div = document.createElement('div');
    div.innerHTML = 'test';
    div.custom_Listener = function(){removeDiv(this)};
    ctnr.appendChild(div);
    div.addEventListener('click', div.custom_Listener , false);
}

But since your using the same listener in every div its even better not to use a separate function for every div but the same (demo):

var ctnr = document.getElementById('ctnr');
var listener = function(){
    removeDiv(this);
};

functionremoveDiv (d) {
    alert('testing');
    d.style.backgroundColor = '#36f';
    d.removeEventListener('click', listener, false);
}

functionaddDiv () {
    var div = document.createElement('div');
    div.innerHTML = 'test';
    ctnr.appendChild(div);
    div.addEventListener('click', listener , false);
}

Post a Comment for "Removing Event Listeners On Automatically Created Multiple Elements"