Blog

Event binding on dynamically created elements in Javascript?


Event Binding on Dynamically Created Elements in JavaScript

Dynamic elements typically refer to items that are generated by JavaScript code rather than existing within the HTML of a page. Event binding is the process of associating an event handler with an event such as click, keypress, mouseover, etc.

Binding Events on Dynamically Created Elements

Event binding on dynamically created elements requires extra attention as they are not present in the DOM at the time the binding is done. The following methods demonstrate how to apply event binding on dynamically added elements.

Method 1: Event Delegation

This approach makes use of event bubbling and event delegation. You assign a single event handler to one of the parent elements, or higher in the DOM hierarchy and then you can use the relatedTarget property of the event object to find the element being clicked and determine if it is a match for the dynamic element that you are searching for.

Method 2: Event Cache

In this approach, an array is created to store all of the events that are to be applied to the dynamic elements. When the code for generating the dynamic elements runs, the array of events is looped through and the events are applied to each generated element. This approach can be applied to events that are called multiple times.

Method 3: Use jQuery

In jQuery, you can use the on() method to bind an event handler to an element. The on() method enables event delegation and can be used to bind an event handler to a parent element and it will handle the events that are fired by the dynamically created elements.

Conclusion

Event binding on dynamically created elements is a common requirement that can be achieved by using one of the methods outlined above. Each of these methods has its own advantages and disadvantages and can be used depending on the individual’s situation.

sa3dy

Mostafa Saady, Egyptian Software Engineer, supersonic self-learner and teacher, fond of learning and exploring new technologies and science. As a self-taught professional I really know the hard parts and the difficult topics when learning new or improving on already-known languages. This background and experience enables me to focus on the most relevant key concepts and topics.

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Check Also
Close
Back to top button