bondythegreat
bondythegreat

Reputation: 1409

how to make live click event on new added DOM

i am a live() user and i know somehow live() is deprecated. i've tried to use bind() to have the event on new added dom working, but it's not.

can you please tell me how to do bind() properly ? or is there any other method to do this task?

this is the html:

<table>
    <tr>
        <td> hi there <span class="click">click me</span></td>
    <tr>
    <tr>
        <td> hi there2 <span class="click">click me</span></td>
    <tr>
    <tr class="end">
        <td></td>
    </tr>
</table>
<button class="add_new">add new row</button>  

this is the js :

var new_row = '<tr><td> hi there, new row! <span class="click">click me</span></td><tr>';

$('.add_new').click(function() {
    $('.end').before(new_row);    
});


$('.click').bind('click', function() {
   alert('clicked');
});

if possible, i want to use native jquery's method and not plugins. this is my jsfiddle http://jsfiddle.net/bondythegreat/z3uXH/

Upvotes: 1

Views: 941

Answers (3)

m90
m90

Reputation: 11822

As of jQuery 1.7+ live() is replaced by on(). The doc pages for live() have a guide how to update to newer methods.

In your case that would translate to:

$('table').on('click','.click', function() {
   alert('clicked');
});

See an altered & working fiddle

Upvotes: 1

jfriend00
jfriend00

Reputation: 707696

You need to use the dynamic version of jQuery's .on() or .delegate().

$('table').on('click', '.click', function() {
    // your code here
});

For dynamic behavior using delegated event handling, the basic idea is that the first select (in the jQuery object) must be a static parent object that is not dynamically created after the event handler is installed. The second selector which is passed as the second argument to .on() is a selector that matches the specific item you want the event handler on. These items can be dynamically created after the event handler is installed.

Using .click() or .bind() gets you static event handlers that only work on objects that are present at the time the code is initially run.

To make this code more robust, I'd suggest two things. First, don't use a class name like "click" that is very easy to confuse with an event. Second, put an id on your table, so that ID can be referenced in the first selector rather than the very generic "table" that may accidentally be active on other tables in your page.

Upvotes: 5

neoascetic
neoascetic

Reputation: 2546

You need to use jQuery's on() method

Like so:

$('table').on('click', '.click', function() {
   alert('clicked');
});

Upvotes: 1

Related Questions