1

I need to add html unit by onclick a button,

<div class="unit">
....
<a class="add">Add</a>
</div>

in jquery,

// add function
$('.add').on('click', function (e) {
.....
});

This is working without any issues. My problem is, I'm adding the same html unit and I need to add more units. I know I need to initialize the add function again inside the add function. Then it is working.

// add function
$('.add').on('click', function (e) {
.....
    $('.add').on('click', function (e) {
    .....
    });
});

But I have more codes inside the add function, So how can optimize it without adding twice ?

user3027118
  • 125
  • 1
  • 9

2 Answers2

1

Use event delegation, you can delegation event to static parent of element being added dynamically. In your case if .unit is static then you can delegation event to it for .add

$('.unit').on('click', ".add" function (e) {
   .....
});

If .unit is not static parent or you do not know static parent then delegate it to document.

$(document).on('click', ".add" function (e) {
   .....
});

Delegated events

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers

Adil
  • 146,340
  • 25
  • 209
  • 204
1

Then you should probably need event delegation,

$(document).on('click', ".add" function (e) {

});

Note : i just used document to delegate the event, but you should use any closest static parent to the element which is having the class add

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130