22

I've got a JavaScript-function that sets the "onclick"-event of some HTML-Nodes - even if that "onclick"-event has been set before.

How can i check if that event has already been set, so I can extend my function to set the event only on HTML-Nodes where it has not already been set?

Ahmad Baktash Hayeri
  • 5,802
  • 4
  • 30
  • 43
user4531
  • 2,525
  • 7
  • 30
  • 38

3 Answers3

18

Check, like this:

if(typeof someNode.onclick == "function") {
   // someNode has an event handler already set for the onclick event...
}

By the way, if you are using a library, you should say so - if you are, it might be easier/cleaner and would differ based on which library you are using...

Jason Bunting
  • 58,249
  • 14
  • 102
  • 93
10

It should be possible to detect event handlers attached using <element>.addEventListener() by intercepting calls to the function:

var myListOfAddedEvents = [];

var realAddEventListener = HTMLElement.prototype.addEventListener;

HTMLElement.prototype.addEventListener = function(evtType,fn,cap) {
    myListOfAddedEvents.push(
        {on: this, type: evtType, handler: fn, capture: cap}
    );

    return realAddEventListener.apply(this, arguments);
};

Note: That is untested code and may need some work. I'm hoping this same function will be used by all element types, but I could be wrong. Also it will only work if you can run this bit of code before they start adding events. A copy for attachEvent could be constructed similarly.

joeytwiddle
  • 29,306
  • 13
  • 121
  • 110
  • You may want to combine this with Jason Bunting's technique. Because there are two ways to register event handlers, we need to use two different techniques to find them! – joeytwiddle Aug 29 '15 at 09:02
1
<input type="button" id="foo" name="foo" value="bar" />

<script type="text/javascript">
    alert(document.getElementById('foo').onclick); //undefined
</script>

So what you want to do is something like this:

<script type="text/javascript">
    if (undefined == document.getElementById('foo').onclick)
    {
        // Add event handler
    }
</script>
Philippe Gerber
  • 17,457
  • 6
  • 45
  • 40