5

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Hellion
  • 1,740
  • 28
  • 36

1 Answers1

3

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

raphael
  • 176
  • 1
  • 9
  • As it turns out, the event that I'm trying to detect is defined via jQuery (as a live() event). I do have jQuery at my own disposal, but rummaging through the API info at the jQuery.com site, I still don't see anything about detecting pre-existing events, only info on how to bind my own events. – Hellion Jan 08 '10 at 23:18
  • oh, in this case: http://stackoverflow.com/questions/1236067/test-if-event-handler-is-bound-to-an-element-in-jquery – raphael Jan 09 '10 at 00:06