Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add click function to dynamically created html tags

So I have a div that contains a number of other divs. Each of these other divs has a class called record. I only use this class to select all of these divs.

<div id = "resultContainer">
   <div class="record">result1</div>
   <div class="record">result2</div>
   <div class="record">result3</div>
   <div class="record">result4</div>
</div>

I also add a click event=

$(".record").click(function(e) {
        do stuff here....
    });

Now I want to dynamically add another div.

$("#resultContainer").append("<div class='record'>result5>/div>");

But now that click event is not added to the record.

My idea was to create a function called update() that executed the $(".record.... code and call the function each time I added a record. But then the original divs do the action more than once!

How do I get all of my divs, regardless of when they were added, to before the do stuff here... exactly once when clicked?

thanks!

In addition, I also have buttons on the dynamic div. So a solution that was able to handle something lik this: $(".save").button({ icons: { primary: 'ui-icon-disk' }, text: false }); would be preferable.

like image 413
kralco626 Avatar asked Dec 21 '10 18:12

kralco626


2 Answers

Don't use .live() in this case. This is a perfect situation for jQuery's .delegate() method, which is more efficient.

$("#resultContainer").delegate('.record','click',function() {
    // do stuff here...
});

Only clicks inside the resultContainer need to be processed to see if they match .record, where .live() will need to process every click on the page.

like image 98
user113716 Avatar answered Sep 22 '22 17:09

user113716


http://api.jquery.com/live/:

Attach a handler to the event for all elements which match the current selector, now and in the future.

$(".record").live("click", function(e) {
    //do stuff here... 
});
like image 30
Emmett Avatar answered Sep 24 '22 17:09

Emmett