1

$(document).ready(function () {

   $('.add-button').on('click', function () {
  
      $('.alert-button').after('<button type="button" class="alert-button">Click me! </button><br>');
  
  });
  

  $('.alert-button').on('click', function () {
  
    alert('HI!');
  
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type='button' class="alert-button">Click me! </button><br>
<button type="button" class="add-button">Add button!</button>

Hi! My " $('.alert-button').on('click'..." code works on elements created on page load, but not on dinamically created ones.

So i have a page with 2 buttons (please run the snippet above). If you click on "Click me!" alert "Hi!" appears.

But when I duplicate "Click me!" button via pressing "Add button", a click on the duplicated "Click me!" produces no alert "Hi!" (although it also has ".alert-button" class).

I want to see alert "Hi!" when I click on any "Click me!" button.

what am I doin' wrong?:)

Sergej Fomin
  • 1,415
  • 3
  • 14
  • 36
  • 1
    https://jsfiddle.net/fb3m2mex/ Is what you're looking for. – maxshuty Jun 14 '17 at 18:35
  • @maxshuty - yes, it does! where can I read documentation about that? I really don't understand how event handlers work in js.... – Sergej Fomin Jun 14 '17 at 18:38
  • 1
    https://api.jquery.com/on/ is a good start. Just so it's clear this is jQuery we're doing here. Basically I think your confusion was that your handler would work for the new elements, but really it only works for the one's that already exist on the page, not new ones that are created. :) – maxshuty Jun 14 '17 at 18:41
  • Handlers won't work on strings of HTML. You need to formally create the element (via `document.createElement()`) and then you can bind a handler to it. – Scott Marcus Jun 14 '17 at 18:42
  • @SergejFomin See [learn.jquery.com](https://learn.jquery.com/events/event-delegation/) for some insights – empiric Jun 14 '17 at 18:45

2 Answers2

3

Just replace this function :

$(document).on('click','.alert-button', function () {

    alert('HI!');

});

This will also bind the click event on dynamically added element.

Vivek Doshi
  • 46,471
  • 9
  • 84
  • 100
0

The click handler is only bound to elements that already exist. You'll need to add handlers to elements as they're dynamically created. In your case, the best place to do that is in the .on function right after the new element is created.

  • thanx, Ben, but I don't understand how can I add a handler in the .on function after the new element is created..... – Sergej Fomin Jun 14 '17 at 18:34
  • After your `after()` method runs, in the next line, assign an event handler to `.alert-button` (or whatever you prefer). – Ben Schroeder Jun 14 '17 at 18:36