Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
67
rated 0 times [  69] [ 2]  / answers: 1 / hits: 39328  / 13 Years ago, thu, january 12, 2012, 12:00:00

I add an event listener to an element:



/* sitepoint.com/javascript-this-event-handlers */
function AttachEvent(element, type, handler){
if (element.addEventListener){
element.addEventListener(type, handler, false);
}else{
element.attachEvent(on+type, handler);
}
}

window.addEventListener(load, function() {
var els = getElementsByClassName('name', 'img');
var elsnum = els.length;
if(elsnum) //found
{
var i = 0;
for(i=0; i < elsnum; i++)
{
var the_els = els[i];
AttachEvent(the_els, click, myfunction);
}
}
}, false);


Later in myfunction, I want to remove the handler again, to prevent duplicate clicks:



function myfunction(e) {
e = e || window.event;
var target = e.target || e.srcElement;

//more code
//...

//remove click handler
target.removeEventListener('click', e, false);

//more code
//...
}


The event listener is not being removed, though. When I click on one of the elements, the code of myfunction is executed again. How can I remove the event listener to prevent the clicked element from being clicked again?



PS: I do not use jQuery.


More From » listener

 Answers
48

I believe you're almost there, but you have to pass the listener to removeEventListener, not the event itself. So try:



target.removeEventListener('click', myFunction, false);

[#88050] Wednesday, January 11, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
saulthomasb

Total Points: 326
Total Questions: 98
Total Answers: 93

Location: Jordan
Member since Sun, Dec 26, 2021
2 Years ago
;