How to determine if Javascript object is an event?

Tom picture Tom · Sep 22, 2009 · Viewed 39k times · Source

What is the safest way to determine if a Javascript object is an event?

Answer

Paul Dixon picture Paul Dixon · Sep 22, 2009

It's fairly good practice to probe possibly "unknown" objects for the properties and methods you expect to find.

So, assume you have got an event object, and probe it before acting on it, e.g.

if (event.target)
{
   //looks like we're an event, hide the target
   var e=$(event.target);
   e.hide();
}

It's important to note that I'm NOT suggesting you test for 'target' to see if its an event: you're testing for target because you're about to use that property. What I'm driving at is that instead of trying to figure out whether an object is event, probe the object to see whether it is going to behave in the way you expect, then use those behaviours.

Code like this should degrade gracefully on browsers with different support, or let you take advantage of browser-specific extensions, e.g.

if (event.initKeyEvent)
{
    //gecko 1.9+
    event.initKeyEvent(...)
}