skip to Main Content

I’m trying to a little script that would click a button when the page is loaded or even better when the script XYZ.js is loaded.

The script I have done works, but only if I add a delay to it. Which is a bit confusing because it normally should also work without adding a delay.

WORKS

window.addEventListener("load", function() {
    setTimeout(function() {
    var button = document.querySelector(".myJS-Button");
        if (button) {
            button.click();
        }
    }, 1);
});

DOESN’T WORK

window.addEventListener("load", function() {
    var button = document.querySelector(".myJS-Button");
    if (button) {
        button.click();
    }
});

2

Answers


  1. it’s likely because the button hasn’t fully loaded or rendered by the time the script is executed
    try this instead :

    document.addEventListener("DOMContentLoaded", function() {
        var button = document.querySelector(".myJS-Button");
        if (button) {
            button.click();
        }
    });
    
    

    edit :
    im not sure what’s the problem i tried the same code with a link and it worked :

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
      </head>
      <body>
        <a class="myJS-Button" href="google.come" target="_blank">BUTTON</a>
      </body>
      <script>
        window.addEventListener("load", function () {
          var button = document.querySelector(".myJS-Button");
          if (button) {
            button.click(); 
          }
        });
      </script>
    </html>
    
    Login or Signup to reply.
  2. It worked liked this

    html file

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
        <script src="./index.js" defer></script>
      </head>
      <body>
        <button class="button" onclick="showmessage();">My Button</button>
      </body>
    </html>
    

    Javscript File

    const button = document.querySelector(".button");
    
    button.click();
    
    function showmessage() {
      console.log("Button Was Cliked");
    }
    

    Here’s the console

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search