I am dynamically adding events using addEvent("keydown", function() {});
to an element. My problem is that there are times when this code get's run on the same element twice or more. The behavior becomes clunky as the function registered for that event runs a couple of times.
Is there a way for me to only run the code above only once on an element? Maybe check if the event has already been added before?
Either don't use a new function each time, or use a class or something to tell you you've added it.
Not using a new function each time
MooTools'
addEvent
is a fairly thin wrapper onaddEventListener
/attachEvent
, which won't add the same function twice. So if you ensure you're using the same function, you can calladdEvent
again without it doing anything:then:
Live Example:
Remembering you've added it:
Live Example:
Maybe your problem is not where or when to add event handler, but how to add. It is possible to delegate events to parent element. For example, this is a classic way of adding an event handler directly to the target element.
And, of course, only the first paragraph has click event.
And below is an example of event delegation.
Since event listener is assigned to a parent for all of its children, all paragraphs will have the click event, no matter when and where they are created. It is very useful when you are adding elements into the page dynamically.
I do not know how much this helps, but it's good to know.
Element.Delegation