0

I have Javascript code that is supposed to do stuff on a click, but it isn't doing anything. It's essentially a button on a pane that slides in. When I click the button, I expect something to happen. This button, though, is populated when an AJAX call completes because the AJAX call is fetching some HTML that contains the button.

Here's my code to set up the button:

$("#btn-delete-setup").on("click", function() {
  console.log("clicked");
    _deleteFunction();
    //return false;
});

Because the Javascript is loaded before that pane and button are rendered from the AJAX call, does this mean the button will not respond to my .on("click") code? Is my button not responding because when Javascript loads, it hasn't found the button to bind to?

Jack
  • 5,264
  • 7
  • 34
  • 43

3 Answers3

1

This button, though, is populated when an AJAX call completes

So this is the perfect case for event delegation, which means binding events on the element which was not available when page was loaded, so you need to delegate the event to the closest static parent:

$("closestStaticparent").on("click", "#btn-delete-setup" function(e){
     console.log("clicked");
     _deleteFunction();
     //return false;
});

$("closestStaticparent") is the page element like any div container/wrapper or i would say the element which is in the dom before ajax call.

Although $('body'), $(document) or $(document.body) are always available for delegating the event.

Jai
  • 74,255
  • 12
  • 74
  • 103
1

So, the answer of your question is : No, this code won't work if the element is appended after the script is loaded (e.g. on document ready).

But you can achieve this easily with jQuery :) :

$(document).on("click","#btn-delete-setup", function() {
    console.log("clicked");
    _deleteFunction();
    //return false;
});

Full solutions offered to you on this post (duplicate): Using jQuery 'click' function that was loaded with Ajax content?

Community
  • 1
  • 1
enguerranws
  • 8,087
  • 8
  • 49
  • 97
0

If you're affraid about the possibility that your button is not ready try with:

$(document).ready(function(){
$("#btn-delete-setup").on("click", function() {
  console.log("clicked");
    _deleteFunction();
    //return false;
});
});

Hope this helps,