user3386779
user3386779

Reputation: 7175

call onload function onload

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">

Upvotes: 2

Views: 36

Answers (1)

Unmitigated
Unmitigated

Reputation: 89139

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">

Upvotes: 1

Related Questions