attachEvent inserts events at the begin of the queue while addEventListener appends events to the qu

Posted by Marco Demaio on Stack Overflow See other posts from Stack Overflow or by Marco Demaio
Published on 2010-04-13T12:23:33Z Indexed on 2010/04/13 13:32 UTC
Read the original article Hit count: 830

I use this simple working function to add events:

function AppendEvent(html_element, event_name, event_function)
{
   if(html_element)
   {
      if(html_element.attachEvent) //IE
         html_element.attachEvent("on" + event_name, event_function);
      else if(html_element.addEventListener) //FF
            html_element.addEventListener(event_name, event_function, false);
   };
}

While doing this simple test:

AppendEvent(window, 'load', function(){alert('load 1');});
AppendEvent(window, 'load', function(){alert('load 2');});

I noticed that FF3.6 addEventListener appends each new events at the end of the events' queue, therefor in the above example you would get two alerts saying 'load 1' 'load 2'.

On the other side IE7 attachEvent inserts each new events at the begining of the events' queue, therefor in the above example you would get to alerts saying 'load 2' 'load 1'.

Is there a way to fix this and make both to work in the same way?

Thanks!

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about event-handling