Attaching Event Listeners in JavaScript

Everybody knows how different is to attach event listeners under different browsers. Under IE is attachEvent(), while under FF is addEventListener()! The compatibility can be checked in the PPK site www.quirksmode.org where the author describes in detail where a given event listener can be registered and how it should be done.

Event Bubbling

Important part of the events in JavaScript is the so called “event bubbling“. You know, when you click on a given DOM element when bubbling is on the DOM elements containing this specific DOM element receive the event. So when I move the mouse over a DIV element the event mousemove is received in every element containing that DIV up to the window object.

In Mozilla it should look like this:

element.addEventListener('mousemove', callback, false);

Where the third parameter is describing the use of event bubbling, when setup to false, and if it’s set to true the other type of event handling is used, the so called capturing, which in breaf is the oposite of bubbling and the event is propagated from the top to bottom. The problem under different browsers is that sometimes this “mousemove” is not enough. In the case of mousewheel there are several combinations.

In IE:

document.attachEvent('onmousewheel', function(e){
     if (!e) var e = window.event;
     e.returnValue = false;
     e.cancelBubble = true;
     return false;
}, false);

In Safari:

document.addEventListener('mousewheel', function(e){
    e.stopPropagation();
    e.preventDefault();
    e.cancelBubble = false;
    return false;
}, false);

In Opera:

document.attachEvent('mousewheel', function(e){
    if (!e) var e = window.event;
    e.returnValue = false;
    e.cancelBubble = true;
    return false;
}, false);

In Firefox:

document.addEventListener('DOMMouseScroll', function(e){
    e.stopPropagation();
    e.preventDefault();
    e.cancelBubble = false;
    return false;
}, false);

Note the differences between all the browsers.

Related posts:

  1. OpenLayers disable mouse wheel on zoom
  2. Flex Javascript communcation example
  3. mouseclick outside a DOM element
  4. Remove DOM Element with JQuery
  5. ExternalInterface from JavaScript to IE/Firefox
  6. cancel bubbling on element click with jQuery
  7. Prevent link default action when mousedown and mouseup fires!
  8. JavaScript closures in brief
  9. jQuery live() vs bind() performance
  10. Event driven programming with jQuery – (part 3). What is a module?