Reputation: 75
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
Upvotes: 1
Views: 2139
Reputation: 1612
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>
Upvotes: 0
Reputation: 161
try this..
$('button').on('click', function(){
//in real life s is loaded via ajax
var s="<p id='twoP' >two</p>";
$('#one').append(s).ready(function(){
alert('ok');
});
})
this will load the element then will fire the call back
Upvotes: 1
Reputation: 44087
You can't use the onload
event there. Why not just have the alert
statement at the end of your event handler?
$('button').on('click', function(){
//in real life s is loaded via ajax
var s="<p>two</p>";
$('#one').append(s);
alert('ok');
})
Upvotes: 1