views:

20

answers:

1

There are 24 div-objects waiting/listening for a mouse-click. After click on one div-object, I want to remove the eventlistener from all 24 div-objects.

for (var i=1;i<=24;i++){
    document.getElementById('div'+i).addEventListener('click',function(event){
        for (var z=1;z<=24;z++){
            document.getElementById('div'+z).removeEventListener()//Problem lies here
        }

        //Some other code to be run after mouseclick

        },false);

}

The problem is that the removeEventListener is nested in addEventListener and I need to define type, listener, caption as attributes to the removeEventListener method. And I think it is impossible to define the listener because of nesting.

I also tried to define a function name, but it didn't worked:

for (var i=1;i<=24;i++){
    document.getElementById('div'+i).addEventListener('click',function helpme(event){
        for (var z=1;z<=24;z++){
            document.getElementById('div'+z).removeEventListener('click',helpme,false);
        }

        //Some other code to be run after mouseclick

        },false);

}
+2  A: 

It should work with a named function. If your second approach does not work properly, try storing the initial listener into a variable, like this:

var handler = function(event) {
    for(...) {
        removeEventListener('click', handler, false);
    }
};

addEventListener('click', handler, false);

Ps. if you care about speed, you may wish to consider using just one event handler. You can put the handler into the parent element of the divs, and then delegate the event from there. With 24 handlers your current approach probably doesn't have a very big performance hit, but this is something you should keep in mind if it ever feels slow.

Jani Hartikainen
Hi Jani! It worked!I wanna thank you so much! I tried to figur out all day long without any success
Woho87