bitclip
bitclip

Reputation: 187

Click button with Javascript after page load / as soon as element loads

I've checked many other answers on StackOverflow but none of them work for some reason.

I'm trying to use something simple like

window.onload = function() {
    sleep(5000)
    clickButton()
}

But as far as I can tell the button on a page I want clicked loads AFTER page load. So window.onload doesn't work at all. That's why I tried to use a custom sleep function to force the code to run after-after page load but nope. Code "sleeps" by preventing page from fully loading, then runs clickButton(), then the page loads. Useless.

I know my actual button clicking code works in practice because I just fed into the browser console line by line and it worked fine. But the button I'm targeting loads after my code is executed!

I have also tried these which also do not work:

window.addEventListener('load', function () {
   clickButton()
})

setTimeout(clickButton(), 5000)

setInterval(clickButton(), 5000)

...

Also I'm using: document.querySelector("[data-a-target='button-name']");

instead of: document.getElementById("button-name");

since this button does not have an id.

...

Also I have never used jquery before if that is the answer.

...

How on earth do I get js to click a button immediately as soon as it loads?

Upvotes: 0

Views: 2853

Answers (1)

ArtInLines
ArtInLines

Reputation: 90

The order in which you write your code plays an important role here.

Firstly, put the script tag at the very bottom of the body element of your html page. That forces the browser to have already read through the entire html page before getting to the script tag with your Javascript.

Secondly, I assume you have an event listener for a click on the button. Write the event listener before you let the button be clicked.

For example, I wrote this little code to test my assumption out:

button.addEventListener('click', function () {
    console.log('Clicked');
});

button.click();

This should hopefully work for you too. Good luck

Upvotes: 1

Related Questions