0

I have a webpage with 2 tabs and a <div id="content"> area which is updated. When you click a tab, jquery performs an AJAX call which retrieves the relevant data from the database and inserts it into the <div id="content">. The content is generated with jquery, mostly using $("#content").append('whatever...'). This works fine.

The problem is when I try to click a button which was created from the original jquery call. It doesn't work. I'm assuming that this is because my jquery script was loaded before this html code was generated, right?

So, my question is, how do I get my generated content to work with my jquery script?

I'm guessing it would be possible for me to create 2 divs: and then use jquery to hide/show the relevant div. Is this a possible solution or is there a more standard way?

Extra info:

  • Wordpress site
  • $wpdb used for database interaction
  • use wp_enqueue_script() to enqueue my jquery script

Thanks:)

liverpaul
  • 169
  • 1
  • 1
  • 11
  • The generated code should also contain the code which should bind events to the dynamically generated content – linktoahref Feb 28 '16 at 08:49
  • 2
    you can either re-bind (unbind/bind) actions for newly created elements or look into event delegation – Igor Yavych Feb 28 '16 at 08:49
  • I will read more about event delegation. That seems to be what I'm looking for. I will leave the thread open for other answers before marking it a solved. Thanks. – liverpaul Feb 28 '16 at 08:58

1 Answers1

1
$(staticParent).on('click', dynamicChild, function() {});

so

$("#bar").on('click', function(){
    $("#foo").append("<input type='button' />");
});
$("#foo").on('click','input', function(){
    alert('Hello World');
});

<p id="bar">Klik Me!!</p>
<div id="foo"></div>

https://jsfiddle.net/adgx7e35/