0

I have a popup confirmation plugin that is triggered when you click on it (to make sure the user wants to do a specific action). The plugin is working perfectly on links on the page using this code:

$('.confirmation-callback').confirmation({
         onConfirm: function(event, element) { 
               alert('hello');
          }
      });

But now the problem is when I create "new" elements via ajax on the page, they are not bound to the code above, and when you click on the new elements nothing happens.

I know the problem is that I need to use the on() function to ensure all events are captured on dynamically generated elements. I have read answers such as here and here that give various versions of it.

I've tried a few things to change the code to work for on() - but I cant seem to get it to work.

I tried just wrapping the whole thing in an on() call:

$(document).on("click",".confirmation-callback",function(){ 
    alert('i see this message');    <<---- I see this on the new elements
    $('.confirmation-callback').confirmation({
             onConfirm: function(event, element) { 
                   alert('but this alert never shows'); 
              }
          });
});

But although I see the first alert, the rest of the confirmation() function is never called.

So how do I force the confirmation() function to run when on() is run?

Community
  • 1
  • 1
Laurence
  • 58,936
  • 21
  • 171
  • 212

2 Answers2

1

The trick here is to bind the event when the AJAX call has been successful. jQuery plugins typically don't listen for addition of new DOM elements, and author assume that we leverage callbacks from AJAX (or other functions that add elements dynamically to the DOM) to bind events to newly added elements.

What you can do is to use the .success() or better, .done() (the former has been deprecated):

$.ajax({
    // Do ajax magic here
})
.done(function( data ) {
    $('.confirmation-callback').confirmation({
         onConfirm: function(event, element) { 
               alert('hello');
         }
    });
});

Even better: bind events only to newly added elements, with a selector of sorts.

Terry
  • 63,248
  • 15
  • 96
  • 118
1

You can do this:

  • First set some flag on non-ajax'ed content
  • Second, use the $(document).ajaxSuccess to rebind those, which is not yet binded.

Like this:

$(document).ready(function () {
    $('.confirmation-callback').confirmation({
        onConfirm: function (event, element) {
            alert('hello');
        }
    }).attr('data-bound', 'true');
}).ajaxSuccess(function () {
    $('.confirmation-callback:not([data-bound="true"])').confirmation({
        onConfirm: function (event, element) {
            alert('hello');
        }
    })
});
Amit Joki
  • 58,320
  • 7
  • 77
  • 95