0

I'm using infinite scroll made by Paul Irish which adds new content from paginator dynamically. I do get my other jquery's to work with .on method, but how to use it with .each? All I have come up with is it will fire multiple times or doesn't work at all on dynamically added items.

My code:

function delete() {
    $('.delete').each(function(index, value) {
        var id = $(this).data('id');

        $(this).on("click", function() {
            if (confirm('Are you sure you want to delete this?')) {
                $(this).parents('.feed').fadeOut();

                var suggests = $.ajax({
                    type: 'post',
                    datatype: 'html',
                    data: "id=" + id,
                    url: 'http://localhost/delete',
                    success: function(data) {}
                });
            }
        });
    });
};
Koen Peters
  • 12,798
  • 6
  • 36
  • 59
EmJeiEn
  • 1,343
  • 5
  • 17
  • 30
  • 2
    Delegate from the document: `$(document).on("click", ".delete", yourEventHandlerFunction);` [source](http://stackoverflow.com/a/15090957/2476755) – royhowie May 16 '15 at 21:27
  • http://stackoverflow.com/questions/16062899/jquery-doesnt-work-after-content-is-loaded-via-ajax – Satpal May 16 '15 at 21:28
  • 1
    What @royhowie said. Or less pretty option: `$(this).off('click').on('click')...` – Johan May 16 '15 at 21:33
  • no, you want the `yourEventHandlerFunction` to be the anonymous function passed to `$(this).click`. You may have to adapt the callback, though. – royhowie May 16 '15 at 22:13
  • @royhowie if I understood correctly, adding: $(document).on("click", ".delete", delete); to fire up the function on click causes the future clicks to be fired up multiple times. For example if I delete one post and decide to delete the other one, for the other one it fires two times. And sorry, I deleted earlier message, I pressed enter accidentaly :) – EmJeiEn May 16 '15 at 22:13
  • Ok so thanks @royhowie and Johan for answers but with my limited skills (quite new to jquery) I really have no idea how to start to make this. If either of you could answer with bit more details, great! – EmJeiEn May 17 '15 at 11:28
  • ah, actually got it to work with callback thanks to answer of @Johan using .off method. Thanks! – EmJeiEn May 17 '15 at 13:18

0 Answers0