Ad

Onload Not Working When Using Jquery Append

- 1 answer

I need to fire the script when elements are loaded via ajax and appended to the DOM.

here is HTML

<div id="one">
  <p>one</p>
  <button>Append</button>
</div>

and here is javascript

$('button').on('click', function(){
  //in real life s is loaded via ajax
  var s="<p onload='myalert();'>two</p>";
  $('#one').append(s);
})

function myalert() {
  alert('ok');
}

The alert will never fire. How to catch the event when elements are fully loaded?

Here is codepen sandbox for playing around: https://codepen.io/xguntis/pen/rQERmW

Ad

Answer

I tried to fix your issue. So I found a way to fix your problem. This is my code

$('button').on('click', function(){
  //in real life s is loaded via ajax
  var s="<p>two</p>";
  $('#one').append(s).ready(function(){
    alert('ok');
  });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<div id="one">
  <p>one</p>
  <button>Append</button>
</div>

Ad
source: stackoverflow.com
Ad