How to determine if Javascript object is an event?

JavascriptJavascript Events

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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.

Solution 3 - Javascript

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.

Solution 4 - Javascript

You could check if the object has an property originalEvent;

event.hasOwnProperty('originalEvent')

e.g:

// var event
var
  isObject = typeof event  ==='object', // is the given argument an object
  isEvent  = isObject ? event.hasOwnProperty('originalEvent') : false; 
if(isEvent) {
  // var `event` is an event!
} else {
  // var event is NOT an event!
}

Solution 5 - Javascript

This isEvent function checks the constructor for the unknown object, converts it to a string, and then searches that for the known event types:

function isEvent(o){
    //grab the constructor for the unknown object
    var c=o.constructor;
    //convert constructor to string
    var s=c.toString();	
    /* declare IE RegExp pattern to match for 'object [Event]' */
    if(document.all){
        //set regExp pattern for IE
        var ptr=/\[object Event\]/;		
    }else{
        /* declare FIREFOX regExp pattern to match for 'object [*Event]' since it has
           several event types:
    	UIEvent 
    	KeyboardEvent
    	MouseEvent
    	FocusEvent
	    WheelEvent
	    CompositionEvent
        StorageEvent
	    CustomEvent (Requires Gecko 6.0)
	    MutationEvent

        Both Custom and Mutation events are not recognized prior to Gecko 6.0,
        so if you want to use these, adjust regExp accordingly */
	    var ptr=/\[object (Keyboard|Mouse|Focus|Wheel|Composition|Storage)Event\]/;	
    }	
return ptr.test(s);  }

Solution 6 - Javascript

I have the same concern. So I set out to prove, and I got closer to the solution.

function isEvent(a){
	var txt, es=false;
	txt = Object.prototype.toString.call(a).split('').reverse().join('');
	es = (txt.indexOf("]tnevE") == 0)? true: false; // Firefox, Opera, Safari, Chrome
	if(!es){
		txt = a.constructor.toString().split('').reverse().join('');
		es = (txt.indexOf("]tnevE") == 0)? true: false; // MSIE
	}
	return es;
}

I tested this feature in

  • FF and Opera 12.0 on Ubuntu 11.64
  • Safari 5.0 on Wine-Ubuntu
  • G.Chrome 19 and MSIE 8 on WinXP

I hope this helps.

Solution 7 - Javascript

I don't know if there's a sure-fire way to do that, but I think your best shot is duck-typing.

Anyway, depending on the situation you could check if a given object has the expected properties that you want to use, just like Paul pointed out.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTomView Question on Stackoverflow
Solution 1 - JavascriptPaul DixonView Answer on Stackoverflow
Solution 2 - JavascriptFelixView Answer on Stackoverflow
Solution 3 - JavascriptAdam MarshallView Answer on Stackoverflow
Solution 4 - JavascriptMark TeunissenView Answer on Stackoverflow
Solution 5 - JavascriptCypherView Answer on Stackoverflow
Solution 6 - JavascriptpatocardoView Answer on Stackoverflow
Solution 7 - JavascriptPablo CabreraView Answer on Stackoverflow