0

Hi i have a situation similar as the exaple below (see code snippet). When appear "called button" and i click it the associated js event not work.

When i add an new element whit js (in the example through ".append()", but also with adding element after an ajax call to another page), this new element is not "identified" from the exist js code.

Which is the best way to resolve this?

Obviously this is a simple example to explain the problem, but i can not resolve the problem including the code in a function and call it when the new element appear becouse the real js code of included plugins is much to complex.

var calledButton = '<br><button id="called-button">This is the called button</button>'
$("#main-button").click(function() {
  $("#response").append(calledButton);
  $("#response").append("<br><br>Main button clicked");
});

$("#called-button").click(function() {
  $("#response").append("<br><br>Called button clicked");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<button id="main-button">This is the main button</button>

<div id="response"></div>
Lumo
  • 5
  • 3
  • Delegate the click to the parent, https://learn.jquery.com/events/event-delegation/ – Huangism Feb 26 '18 at 14:38
  • **Google search:** jQuery Event delegation – Ele Feb 26 '18 at 14:38
  • The js plugins recognize the element through a class or id when the document loads. I would like resolve it (if possible) adding only new code (or reloding the plugins file) – Lumo Feb 26 '18 at 15:02

0 Answers0