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.innerHTMLwrite ). -
addEventListeneris 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 ).
- onkeypress – keypress
- onblur -> blur
- onfocus -> focus
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
- Instead of returning false. Use
preventDefault()to stop forms from submitting on enter.
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
addEventListenerif possible, can fall back toattachEventfor 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.