0

I am injecting some html strings to create buttons, however they jquery events don't fire after they have been created. I was told they needed to be "initialized" but cannot find an example.

$('#parent_div).html(<div class="clickable-button">click me here</div>);

will create:

<div id='parent_div'>
   <div class="clickable-button">click me here</div>
</div>

And my usual jquery doesn't fire when clicked.

$('.clickable-button').on('click', function (){
console.log('clicked');
}

I got it to work by using a parent that existed before the injection with on()

$('#parent_div').on('click', '.clickable-button', function(){
console.log('clicked');
}

But it seems like there should be a better way to handle this because I don't always know what the parent is and I don't want to hard code new jquery every time I inject something. How do people usually handle this problem?

1 Answers1

0

You can listen at the document level in that case you dont know whats the parent element

$(document.body).on('click', '.clickable-button', function(){
console.log('clicked');
}
uke
  • 893
  • 4
  • 10
  • If you see a comment on a question with the words "Does this answer your question?" and a link, please visit the link and see if it answers the question. If it does, please don't answer the question. If the answers do answer the question, but you have a better answer, add an answer to the linked question. – Heretic Monkey Dec 16 '20 at 18:24