Home > database >  JS - Click button before page load
JS - Click button before page load

Time:12-01

Right now it goes like this:

Page loads and renders, shows content (text, icons and images)

Some ms pass by, button gets clicked.

How can i achieve that my button gets shown as clicked, before it gets rendered as unclicked?

JS im using

document.getElementById("start").click();

CodePudding user response:

Window.onload function will be useful to you as whenever dom content is loaded after that onl oad function will run and parallelly your browser try to render the loaded dom content to the user. So, In most cases, it will be displayed as clicked.

In this, you must have your styling or content you want to display to the user initially on click event-listener. Therefore, when clicking is triggered from onl oad then it will run your mentioned event listener's logic.

window.onload = function() {
  document.getElementById("test").click();
}

document.getElementById("test").addEventListener("click", function(){
   this.style = "background-color: red";
});
<button id="test" style="background-color:white">Button</button>

  • Related