Is it bad to bind an event to an element twice?

For example…

I have some LI elements, where, on page load a function bindHover() binds the hover event handler code I need to that LI element.

Later in my script, I’m appending another LI to that list, sorting the list, and calling bindHover() again, which binds the hover event handler to the newly appended element, but also all of the existing LI elements that already are bound.

Is that bad?

If you’re overwriting the handlers then there’s no problem.
If you’re using a function that appends to any existing handler, then the resulting handler will execute the same code twice, and only you can decide if that’s a problem. The latter applies if you’re applying event listeners rather than handlers.

I think you’re saying I’m ok, because the handler is only executing once per hover. But currently my code binds the handler to the LI’s in the target UL on load, and then again to the LI’s in the same UL after a new LI has been appended…

I don’t think I can just bind the handler code to each new LI because of the way I’m sorting the list items.

No I’m not saying that because I can’t tell without seeing your code, particularly how the event handlers are assigned.


It all depends on how you are binding the event. If you are using something like

li.onmouseover = function(){…}

Then it shouldn’t give you any trouble. However, if you are using event listeners, whether in IE’s way or standard way, then it WILL give you problems. The reason for this is because if you use event listeners then every time you bind an event it does not overwrite the existing function associated to that event. Instead, it just pushes the new function and both are executed when the event fires.

Now, it doesn’t really mater if you are associating functions to the event or using event handlers, you shouldn’t be doing what you are doing the way you are doing it. There are better ways to do it. For example, you could check if the functions has already been assigned to the event before adding it. You could use what I call an observer to keep track of the elements to which the function has been binded already. These are just two ways you could do it, but are not the only ways to do it.