Javascript Event Handlers 'addEventListener' and 'attachEvent' ~ Web CodeHelpers

Javascript Event Handlers 'addEventListener' and 'attachEvent'

The ways of registering event handlers for page elements are:
inline event handlers added as HTML tag attributes, for example: 

  <a href="" onlick="alert('Bye!')">Click me!</a>

event handlers added by assignment (usually right after the page loads), e.g.: 

The above techniques are simple but have certain disadvantages: they allow you to have just one event handler per element.

In addition, with inline event handlers you get very poor separation of JavaScript code from HTML markup.

 Modern browsers provide additional programmatic ways of registering event handlers for page elements, allowing you to dynamically add one or more handlers during the webpage lifetime.

 For example, you can programmatically add handlerFunction as an onclick event handler for an element by using these methods:

  • element.attachEvent('onclick',handlerFunction);
       (in Internet Explorer 5 or newer)
  • element.addEventListener('click',handlerFunction,false);
       (in most non-IE browsers and IE9).

  • The third argument false in addEventListener specifies that the event capturing phase should not be used, and the event should be handled during the bubbling phase of the event propagation.

    You can combine the above calls together in a cross-browser function addEventHandler:

    function addEventHandler(elem,eventType,handler) {
     if (elem.addEventListener)
         elem.addEventListener (eventType,handler,false);
     else if (elem.attachEvent)
         elem.attachEvent ('on'+eventType,handler); 


    Post a Comment

    Subscribe updates via Email