views:

418

answers:

2

Hallo,

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 ?

A: 

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
And, if developer uses something like: button.addEventListener('click', buttonPressed, true); in Mozilla?
this will not work for event handlers set using attachEvent or addEventListener.
Jonathan Fingland
I am aware of that, but since the OP didn't specify how he is wiring things up, I assumed the DOM 0 method of doing so.
Jason Bunting
By the way, this *is* a wiki - feel free to edit my response and add more robust code... :P
Jason Bunting
A: 
<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
this will not work for event handlers set using attachEvent or addEventListener.
Jonathan Fingland
thx! didn't know that :)
Philippe Gerber