Sami Kh
Sami Kh

Reputation: 117

Javascript "load" event not working as expected

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.

Upvotes: 3

Views: 6364

Answers (5)

Akrion
Akrion

Reputation: 18515

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

Upvotes: 1

Harun
Harun

Reputation: 1237

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

Upvotes: -1

Vishak
Vishak

Reputation: 21

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

Upvotes: 1

R.D
R.D

Reputation: 226

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>

Upvotes: 0

Dacre Denny
Dacre Denny

Reputation: 30360

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 recommend using DOMContentLoaded for such things anyway. For more information on this event, see the MDN documentation

Upvotes: 0

Related Questions