Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: What is addEventListener?

Tags:

javascript

What is this function? Didn't really find any good examples.

like image 315
Strawberry Avatar asked Dec 01 '22 10:12

Strawberry


2 Answers

The addEventListener method is the W3C standard method to attach an event handler to an element, so that you can do something useful when an event is triggered. The following example would popup an alert message when the element with id my_image_id is clicked:

function doSomething() {
   alert('Image clicked');
}

var myImage = document.getElementById('my_image_id');

myImage.addEventListener('click', doSomething, false);

Unfortunately this does not work in Internet Explorer, since Microsoft uses a different event registration model. In Internet Explorer 5+, you would have to attach the event handler as follows:

myImage.attachEvent('onclick', doSomething);

Therefore for a cross browser event registration method, you can use reflection and execute conditionally:

function addEventHandler(node, type, f) {
   if (node.addEventListener) {
      node.addEventListener(type, f, false);
   } 
   else if (node.attachEvent) {
      node.attachEvent("on" + type, f);
   } 
   else {
      node["on" + type] = f;
   }
}

var myImage = document.getElementById('my_image_id');

addEventHandler(myImage, 'click', doSomething);

Further reading:

  • Mozilla Dev Center: element.addEventListener
  • Quirksmode: Advanced event registration models
  • Douglas Crockford: The Theory of the DOM
like image 58
Daniel Vassallo Avatar answered Dec 10 '22 20:12

Daniel Vassallo


You may be familiar with adding an event handler like this:

window.onload = function() {
  alert('onload event!');
};

or even in HTML like this:

<body onload="alert('onload event!')">

Well, the downside to this is that you can only have one event handler. So if something else later overwrites that "onload" property, the previous event handler is no longer used.

addEventListener is a way to register an event handler without overwriting a previous one. It's supported by most browsers other than Internet Explorer. No to worry, though, because Internet Explorer has its own equivalent: attachEvent.

Here's a (simplified) example of their use:

        if (myelement.addEventListener) {
            // other browsers
            myelement.addEventListener(eventname, callback, false);
        } 
        else {
            myelement.attachEvent("on"+eventname, callback);
        }

It's usually a better idea to register an event using addEventListener or attachEvent methods than the onload/onsomething property because it will not possibly disrupt any other Javascript code from the same page.

like image 35
thomasrutter Avatar answered Dec 10 '22 19:12

thomasrutter