krampstudio
krampstudio

Reputation: 3611

How to know in JavaScript if an event name is custom?

How can I know if an event is a DOM/HTML Event in JavaScript ?

Let say, I have an element <a>. How can I know that click or focus are native events but another like mycustomevent isn't?

For example, if I want to attach the listener in a different way if the event is native or custom:

var eventName; // can be 'foo', 'click' or 'touchstart';

var link = document.querySelector('a');
if(//custom){
    eventName += '.domain';
}
link.addEventListener(eventName, function (){ //... });

Upvotes: 1

Views: 1319

Answers (2)

user663031
user663031

Reputation:

function isNativeEvent(eventname) {
    return typeof document.body["on" + eventname] !== "undefined";
}

This will check if the event handler is defined on some element (including being null), which means it's a native event.

> isNativeEvent('click')
< true
> isNativeEvent('myCustomEvent')
< false

Upvotes: 3

Radonirina Maminiaina
Radonirina Maminiaina

Reputation: 7004

Javascript native events are listed here: http://en.wikipedia.org/wiki/DOM_events, so if the event you use is not among the list, it's a custom event.

Upvotes: 0

Related Questions