I want to display an alert after the button is displayed i.e., after the page is loaded.
<input type='button' id='lognBtn' value='btn' />
<script>
window.addEventListener("load", function(){ alert(20); });
</script>
Using this code, alert is displayed before page load itself. I tried DOMContentLoaded
too. Please help.
I want to display an alert after the button is displayed i.e., after the page is loaded.
<input type='button' id='lognBtn' value='btn' />
<script>
window.addEventListener("load", function(){ alert(20); });
</script>
Using this code, alert is displayed before page load itself. I tried DOMContentLoaded
too. Please help.
-
Note: DOMContentLoaded event triggers on document when DOM is ready. We can apply JavaScript to elements at this stage. All scripts are executed except those that are external with async or defer and over here you were calling
alert
which is async – Narendrasingh Sisodia Commented Aug 27, 2018 at 5:19
5 Answers
Reset to default 1You can use setTimeout() method to create a delay to call alert after page loads
window.onload = function(){
if(document.getElementById("demo")){
setTimeout(function(){ alert("Hello"); }, 1000);
}
}
<!DOCTYPE html>
<html>
<body>
<button id="demo"></button>
</body>
</html>
It works as expected ... it is just that the alert is a blocking event to the browser and you have to click on it to continue. You can see from the example bellow that the alert shows the button value although the button is not "shown" per-se:
<input type="button" id="loginBtn" value="Login" />
<script>
addEventListener("load", function(){
alert(document.getElementById('loginBtn').value)
});
</script>
You can switch to event handler on the button or use setTimeout as shown here
This may be as simple as swaping the order of <script>
and <input/>
in your HTML:
<script>
document.addEventListener("DOMContentLoaded", function() {
alert(20);
});
</script>
<input type='button' id='lognBtn' value='btn' />
Generally, I would remend using DOMContentLoaded
for such things anyway. For more information on this event, see the MDN documentation
The solution is quite simple. You are using load
so the browser will display it as soon as the page loads. Simply change it to click
like so and you will get the alert after you click on the button, therefore giving you some control over when the alert should appear and giving time for the button to render before the alert.
<input type='button' id='lognBtn' value='btn' />
<script>
window.addEventListener("click", function(){ alert(20); }); //change here
</script>
You can use window.onload
event. Actually, the alert showing after DOM load but you can not detect the difference after button display and then the alert es out. You can use setTimeout
for 1 second.
window.onload = function(){
setTimeout(function(){ alert(20)},1000);
}
<!DOCTYPE html>
<html>
<body>
<input type='button' id='lognBtn' value='helloBtn'/>
</body>
</html>