Example code:
element.addEventListener('click',function () {
this.style.backgroundColor = '#cc0000'
//after element was clicked once what to do here to remove this event ?
},false)
And where to do it, is it possible directly in function where I put the comment?
If you add an event with addEventListener()
you must have a reference to that function available to be able to subsequently remove it.
With an anonymous function that's only possible with arguments.callee
, and then only while you're within the function itself:
element.addEventListener('click', function() {
this.style.backgroundColor = '#cc0000';
this.removeEventListener('click', arguments.callee);
}, false);
but note that this isn't legal in ES5 "strict mode".
Hence it would just be better to give your callback a name and then use that in the call to removeEventLister()
:
element.addEventListener('click', function cb() {
this.style.backgroundColor = '#cc0000';
this.removeEventListener('click', cb);
}, false);
Demo at http://jsfiddle.net/alnitak/RsaVE/
Not truly anonymous anymore, but here is the best I can come up with (using a closure):
(function(){
var handler = function(){
this.style.backgroundColor = '#cc0000'
element.removeEventListener('click', handler, false);
};
element.addEventListener('click', handler, false);
})();
Edit: +1 for Alnitak's revised answer - it's a little more concise than this one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With