Check if the object is a DOM event

From a function like

function eventHandler(e) { // ... } 

is there a reliable and efficient way to determine if an e a DOM event?

+6
source share
3 answers

I do not believe that there is a reliable way to determine if a given object is NOT a DOM event.

  • typeof e will always return 'object' for genuine event objects, which does not help.
  • Any property that you can check on an object can exist both in a genuine Event object and in any object other than an event.
  • You might think that the prototype chain might be useful for defining this, but it has the same problem as # 2 (can be easily replicated).
  • The contructor property may seem promising, but you can do this:
 function DummyEvent(){ this.constructor.toString = function(){ return "function MouseEvent() { [native code] }"; } } 

The result is console.log(e.constructor) print "function MouseEvent() { [native code] }"

So, is there a β€œreliable” way to determine if an object is an event? No.

Edit - Please note that all this does not matter if you want to prevent event spoofing, as you can easily create real events.

 var evt = new Event('click'); var evt2 = document.createEvent('MouseEvents'); evt2.initMouseEvent('click', ...); //etc 

Edit2 - I created the jsFiddle test, trying to find a way to distinguish objects, but I have not found anything specific yet. Please note that I did not point out properties on DummyEvent , because they are obviously easily fake.

+3
source

Perhaps if the event is bubbling event.bubbles through the DOM it DOM event. But even if this statement is true, its distribution can be stopped.

UPDATED :

The OK property you are looking for is e.target and for IE e.srcElement . Both properties return the HTML element in which the event occurred at which it is defined as the DOM.

However, you should probably indicate what you are interpreting as a DOM event. You mean browser events, because this is also a DOM event:

 var zoo = jQuery('#zoo'); zoo.bind('moo'); zoo.trigger('moo'); 

It is attached to the DOM node

0
source

In jquery, I created a testing function, something like this:

 function isEvent(e) { try { e.PreventDefault(); return true; } catch (err) { return false; } 

}

and testing code:

 var o = new Object(); var e = $.Event('click'); alert(isEvent(o)); alert(isEvent(e)); 

the previous warning shows false, while the last shows true. See fiddle .

UPDATE: it is safer to call something like preventDefault instead of a trigger.

-1
source

All Articles