1

I'm currently adding new buttons using append() function.

Since these new buttons were not present on page load, they are not selectable.

I found one way to make it work by placing the code inside of

$(document).on("mouseover", ".container", function() { ...

but it's not reliable. I can't believe it's the only way around, surely there must be something more suitable, right?

$('.button').on('click', function() {
  $('.container').append('<br /><button class="addedbutton">Added button</button>');
})

$('.addedbutton').on('click', function() {
  $(this).hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <button class="button">Add a button</button>
</div>
Mamun
  • 66,969
  • 9
  • 47
  • 59
Steven
  • 167
  • 8
  • Does this answer your question? [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Mark Baijens Jul 07 '20 at 13:24
  • 1
    _“Since these new buttons were not present on page load, they are not selectable.”_ - of course they are _selectable_. They are not part of any selections you made _before_ you added them though. _“but it's not reliable”_ - event delegation _is_ the usual way to handle such issues. You need to at least explain how exactly you consider this to be “unreliable”, instead of just stating that, as if it was an actual established fact. – CBroe Jul 07 '20 at 13:27

1 Answers1

3

Try using delegation approach which will ensure that events will be attached to the elements that are added to the document at a later time:

$('.container').on('click', '.addedbutton', function() {

$('.button').on('click', function() {
  $('.container').append('<br /><button class="addedbutton">Added button</button>');
});

$('.container').on('click', '.addedbutton', function() {
  $(this).hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <button class="button">Add a button</button>
</div>
Mamun
  • 66,969
  • 9
  • 47
  • 59