2

I am trying to auto click on a button with id btn on page load. This is my snippet.

<button id="btn">Click me</button>
<script>
document.getElementById('btn').click();
    alert("h")
</script>

How can I give an alert on page load? Pls help. Thanks.

Reuben Rodriguez
  • 51
  • 1
  • 1
  • 5

4 Answers4

10

function test(){
   alert("Hi");
}

window.onload = function(){
  document.getElementById('btn').click();
  
var scriptTag = document.createElement("script");
scriptTag.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js";
document.getElementsByTagName("head")[0].appendChild(scriptTag);
}
<button id="btn" onclick="test()">Click me</button>
Nishant Dixit
  • 5,388
  • 5
  • 17
  • 29
2

Well the alert currently is happening on page load, because you haven't put it inside an event callback. You presumably meant:

//wait for DOM ready...
document.addEventListener('DOMContentLoaded', () => {

    //...get the button
    let btn = document.querySelector('#btn');

    //...bind the click event
    btn.addEventListener('click', () => { alert('hello'); }, false);

    //...trigger the click event on page enter
    btn.click();

}, false);

Note also the document ready handler, which waits for the DOM to be ready.

Mitya
  • 33,629
  • 9
  • 60
  • 107
2

If you want to give alert on page load than simply use this -

window.onload = function(){alert("I am loaded")};

But if you want to give an alert after page load also by clicking on button use this -

function autoClick(){
  alert("I am loaded and automatically clicked");
}
window.onload = function(){
  document.getElementById('autoClickBtn').click();
}
<button id="autoClickBtn" onclick="autoClick()">Click me</button>
1

Try this:-

   window.onload=function(){
      document.getElementById("btn").click();
      alert('Page Loaded')
    };
    function buttonClick(){
      alert("button was clicked");
     }
<button id="btn" onclick="buttonClick()">Click me</button>
Mr. Roshan
  • 1,777
  • 13
  • 33