Search code examples
javascriptdom-eventscross-browser

Check if object is an event in JS


I have a function that might either be called explicitly or when an event fires. If it's triggered by an event, I need to ignore a function parameter that might otherwise have a useful value.

Is there a reliable, cross-browser way I can check whether an object is an event?

We've been using this, but realized it doesn't work in IE7 since Event is undefined:

var view = {
    save: function (data) {
        if (data.constructor === Event.constructor) {
            // It's an event.
        }
    }
};

Solution

  • I suppose the "poor man's" way would be to just check for the existence of a certain method that all Event objects have - regardless of how they are created:

    if (!(typeof data.altKey == "undefined")) {
      // it's an Event
    }
    

    EDIT

    Since preventDefault isn't accepted in some versions of IE I've changed the solution to use a different property, really any common property should work just fine.