call onload function onload

Viewed 26

I want to call the function on load the

tag.Now I can't call the function.It removed the tag and replace it with on button click.

$('.test_button').click(function(){
 $('#test').remove();
 $('.panel').append('<p id="test" onload="myFunction();">No Data Available<p>');
});

function myFunction(){
alert('No data available');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="panel">
<p id="test">onload<p>
</div>
<input type="submit" class="test_button">

1 Answers

HTML elements, other than the body, do not have an onload event. Since adding elements to the DOM is synchronous, you could just invoke myFunction after appending. If you want the text to be changed before the alert, you can just use setTimeout.

$('.test_button').click(function(){
 $('#test').remove();
 $('.panel').append('<p id="test"">No Data Available<p>');
 setTimeout(myFunction);
});

function myFunction(){
    alert('No data available');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="panel">
<p id="test">onload<p>
</div>
<input type="submit" class="test_button">

Related