I'm about to update my code to use addEventListener()
over just writing to the element property in Javascript.
Before I do this I wanted to verify a few things.
I'm assuming that I do not have to call removeEventListener()
, if I update the DOM and remove the elements ( by .innerHTML
write ).
addEventListener
is supported on the popular modern browsers - IE9, Chrome, Firefox, Safari
There are no other issues that might arise on modern browsers.
I'm asking because I don't want to jump the gun in updating my code.
Notes:
property to event correlations ( remove the on ).
Research
https://developer.mozilla.org/en/DOM/element.addEventListener ( Has compatibility Chart )
http://www.quirksmode.org/js/events_advanced.html
Related
JavaScript listener, "keypress" doesn't detect backspace?
Notes
preventDefault()
to stop forms from submitting on enter.1) You don't need to call removeEventListener for that matter but you will need to call removeEventListener if you remove the DOM element attached to the eventListener via addEventListener, if you remove any of its children you don't need to remove anything.
2) addEventListener is supported on all major browsers
3) There are no other issues on modern browsers related to addEventListener
4) onkeypress is not the name of an event but an attribute, the event name is keypress. Same for other names on* alike
A quick code to avoid jQuery for cross-browser compatibility:
Element.prototype.on = function(evt, fn) {
if (this.addEventListener)
this.addEventListener(evt, fn, false);
else if (this.attachEvent)
this.attachEvent('on' + evt, fn);
};
Element.prototype.off = function(evt, fn) {
if (this.removeEventListener)
this.removeEventListener(evt, fn, false);
else if (this.detachEvent)
this.detachEvent('on' + evt, fn);
};
You don't have to. If you don't store references to the DOM element (in accidental global variables for example), the garbage collector should clean it up.
That's the browser support. For older IEs there is attachEvent()
which does almost the same.
Nothing that you should worry about. This is the modern way to go.
Note: you might want to use jQuery for making things cross-browser. Under the hood it uses addEventListener
if possible, can fall back to attachEvent
for older IE and also normalizes your event object, so you don't have to worry about differences. It is also great for DOM manipulation and traversal.
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