0

I have a button on a webpage which loads after a given amount of time, works well but my client would like an easy way to add a button that calls this function so he can add dynamic values to it.

In this instance the button should remove a class after 5 seconds of the page/element loading:

Problem, the function is not being called, I have checked the reference to the javascript file is correct, I suspect the issue is the way I am calling the function, here is my code:

<a href="somewhere.com" id="myButton" window.onload='showButton("myButton", "5000")'; 
class="invisible">Now you can see me!</a>

function showButton(id, time) {
    setTimeout(function() { showButtonPrep(id, time); }, time);
    console.log("I have fired!");
}
function showButtonPrep(id, time) {
    var button = document.getElementById(id);
    button.classList.remove('invisible');
}

The console does not log the string so I can see it is not being loaded I have tried variations of the load, i.e

window.load
this.load

The javascript file containing the function is in the footer, if I put an alert in top of the javascript file that does fire.

  • You should read [Why is using onClick() in HTML a bad practice?](https://stackoverflow.com/questions/5871640/why-is-using-onclick-in-html-a-bad-practice) and use `addEventListener` instead. `window.onload` doesn't make sense. This way, you can only add an event listener for this specific element. – jabaa Dec 05 '21 at 14:41

1 Answers1

0

window.onload is not a valid HTML attribute for <a>. This seems a mixup between HTML and JavaScript.

You should put that inside a script:

window.onload = () => showButton("myButton", 5000);

function showButton(id, time) {
    setTimeout(function() {
        showButtonPrep(id, time);
    }, time);
    console.log("I have fired! Now wait 5 seconds...");
}

function showButtonPrep(id, time) {
    var button = document.getElementById(id);
    button.classList.remove('invisible');
}
.invisible { display: none }
<a href="somewhere.com" id="myButton" class="invisible">Now you can see me!</a>
trincot
  • 317,000
  • 35
  • 244
  • 286