How to determine if Javascript object is an event? How to determine if Javascript object is an event? javascript javascript

How to determine if Javascript object is an event?


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(...)}


How about using instanceof? As long as the event object was created using the constructor new Event(), for instance:

var e = new Event('click');e instanceof Event; // true

In case of the event parameter in event handlers, although its type is Object, it contains the native event as a property, so this could be used instead:

function myEventHandler(e) {   e.originalEvent instanceof Event; //true}

Here it should be noted that the actual value may vary depending on the browser, specially when the event is a touch event, see here and references within. Not an issue in my case.


Old question, but apparently according to this, event.type is cross-browser:

http://www.quirksmode.org/js/events_properties.html

RameshVel added this in an edit to his answer but it was heavily down-voted.

Of course the safest way is to follow the guidance of the accepted answer, but it just so happened that I want to discard the object if it is an event.