Why Firefox says that window.event is undefined? (call function with added event listener)

I have a trouble in this part:

var ex = {
  exampl: function(){
    var ref=window.event.target||window.event.srcElement; // here
    alert(ref.innerHTML); // (example)
  }
}

This function is called this way:

document.body.childNodes[0].addEventListener('mouseover',ex.exampl,true);

Only Firefox says that window.event isn't defined...

I don't know what to do, to make it work. It works very well in webkit browsers and opera (I can't check it in MSIE and I don't care about it).

Why does it happen?


try getting the event using the parameter passed (named e in this case). i tested this and both window.event and the e is supported in chrome.

try checking for both, whichever exists

var ex = {
  exampl: function(e){

    console.log(window.event);
    console.log(e);  

    //check if we have "e" or "window.event" and use them as "evt"
    var evt = e || window.event    

  }
}

window.event is not a feature, it's a bug!

Quoting MDN:

window.event is a proprietary Microsoft Internet Explorer property which is only available while a DOM event handler is being called. Its value is the Event object currently being handled.

And most importantly:

Not part of any specification.

window.event is non-standard, so don't expect any browsers to support it.

First parameter of callback function in element.addEventListener() is an Event object. Use it instead of window.event.


Because window.event doesn't exist in Firefox. That's because browser have different event models and you'll have to deal with their differences or use a library like jQuery not to have to deal with all the differences between browsers. Welcome to the DOM.


Chrome doesn't have it natively either. Rather than having every event trigger pass its own event object, IE dropped properties into window.event and handed that off. This worked since you're only ever dealing with one event at a time. What every browser should have is window.Event which is the actual constructor for event objects. If you're seeing 'window.event' anywhere but IE8 and below, try opening a console on a blank tab and logging or alerting it there. Chances are something is adding it manually on the page you're looking at.

If you look at crossbrowser normalizing code for event handlers, you'll often see:

if(!e){ e = window.event; }

That's event normalizing code handling older versions of IE. In modern browsers, e should be its own object being passed through arguments, not a reference to a property of window.