Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Javascript EventListener only if no other listener is present?

I'm a relative tyro in the Javascript programming arena, so please go easy on me. :-)

I am trying to add an eventListener to various DOM elements on a page. However, some of the elements I'm adding my event to already have an eventListener, and I don't want to supersede that one; I only want to add my event to an element that doesn't already have an event associated with it.

I've looked through a bunch of stuff relating to addEventListener, event.StopPropagation, event bubbling, and so forth, but haven't figured out any way to accomplish this yet.

Is there a way to detect other event listeners on a given element, or some other way to get where I want?

like image 469
Hellion Avatar asked Nov 06 '22 17:11

Hellion


1 Answers

You can check if the on[event] property of that given element is set by using:

if (typeof(document.getElementById("element-id").onclick) == "undefined") {
  // event undefined
}

if (typeof(document.getElementById("element-id").onclick) == "function") {
  // event defined
}

Notice that this won't work if a javascript library such as jQuery were used to define the event (e.g. by using $("#element-id").click()). I'd recommend you to use jQuery, you can handle events easily with it.

edit: uh, well, afaik it doesn't work if you're using addEventHandler too. It only works if you set your event by using yourElement.onclick = anyFunction

like image 143
raphael Avatar answered Nov 11 '22 08:11

raphael