Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I update to addEventListener?

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.

  1. I'm assuming that I do not have to call removeEventListener(), if I update the DOM and remove the elements ( by .innerHTML write ).

  2. addEventListener is supported on the popular modern browsers - IE9, Chrome, Firefox, Safari

  3. 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.
like image 920
CS_2013 Avatar asked May 17 '12 15:05

CS_2013


2 Answers

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);
};
like image 113
David Diez Avatar answered Sep 21 '22 07:09

David Diez


  1. 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.

  2. That's the browser support. For older IEs there is attachEvent() which does almost the same.

  3. 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.

like image 44
kapa Avatar answered Sep 19 '22 07:09

kapa