0

I have this piece of jQuery code in my page, which basically does some stuff to the <td> in the table based on the server response.

 $('document').ready(function() { 
    $('td a').click(function(e) {
        e.preventDefault()
        var href = $(this).attr('href');
        $.ajax({
            url: href,
            success: function() { 
              [...] // SKIPPED, DO STUFF HERE. 
            },
           }
        );
    })
 })

It works pretty well.... Except one problem. It would only work on the <td> entries that were loaded initially.

If I use an endless pagination (like google images style, or twitter style), where more entries are loaded after some AJAX actions (such as button clicks, scrolling to the bottom, etc), those newly-loaded entries wouldn't work with the dollar sign functions.

What can I do to make it work with all <td> entries?

CuriousMind
  • 15,168
  • 20
  • 82
  • 120

4 Answers4

0

you need execute following code

$(document).on('click', 'td a',function(e) {
    e.preventDefault()
    var href = $(this).attr('href');
    $.ajax({
        url: href,
        success: function() { 
          [...] // SKIPPED, DO STUFF HERE. 
        },
       }
    );
})
Pooja Bohra
  • 120
  • 1
  • 13
0

Use the .on() method which will bind future elements as well:

  $('td').on('click', 'a', function(e) {
    ...
  });
paul
  • 151
  • 4
0

This is clear issue of event delegation:

just change this line:

 $('td a').click(function(e) {

to this:

$(document).on('click', 'td a', function(e) {
Jai
  • 74,255
  • 12
  • 74
  • 103
0

You will want to use the dynamic form of .on() so that it can use delegated event handling to handle events for all newly create elements that match your selector.

The general form is this:

$(static parent selector).on("click", "td a", function(e) {});

The static parent selector should be a parent of the dynamically added elements that is itself not dynamic and is present at the time you run the initial jQuery. It should be as close to the dynamic elements as possible for best performance. In this case, it could easily be the table itself as long as the table DOM object already exists when the initial jQuery code is run.

See these similarly answered questions:

jQuery .live() vs .on() method for adding a click event after loading dynamic html

how to make live click event on new added DOM

jQuery .on does not work but .live does for similarly answered questions.

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979