-2

Something like this but instead for clicking the button have it done by calling it programmatically.

<script>

 function myFunction() 
{
document.getElementById("demo").innerHTML = "Hello World";
}
</script>

button onclick="myFunction()">Click me

id="demo"

  • 2
    To click an element, use `element.click()`. – gyre Apr 17 '17 at 18:09
  • 2
    Show us some code you have already, what you tried etc. Without that, we can explain to you what you did wrong and what you should do instead. – Oen44 Apr 17 '17 at 18:09
  • 1
    Possible duplicate of [How do I programmatically click a link with javascript?](http://stackoverflow.com/questions/902713/how-do-i-programmatically-click-a-link-with-javascript) – BSMP Apr 17 '17 at 18:12
  • The user is asking a high-level question about a topic, as such the lack of code is okay. However, if you do have some code to post, this would enhance the question. – nmg49 Apr 17 '17 at 18:12
  • Also: [Click a button programmatically - JS](http://stackoverflow.com/questions/24278469/click-a-button-programmatically-js) – BSMP Apr 17 '17 at 18:12
  • Or http://stackoverflow.com/questions/24711051/auto-click-script-within-a-browser/24712697#24712697 – Xotic750 Apr 17 '17 at 18:36
  • But why do you need to issue a `click event` when you could just èxecute the `click handler` directly? – Xotic750 Apr 17 '17 at 18:38

3 Answers3

1

I don't think "click for itself" is the right way to think about this problem. A better way would be to modularize the functionality of the button click as such:

doOnClickButton()

Then, when the page loads, simply execute this function.

Example with jQuery:

$(document).ready(function() {
    doOnClickButton();
})
nmg49
  • 1,356
  • 1
  • 11
  • 28
  • The OP is asking about JavaScript, not jQuery. – Oen44 Apr 17 '17 at 18:20
  • 1
    jQuery is Javascript. Yes this can also be done in vanilla js which is fine, but there's also nothing wrong with using jQuery. All it is is a wrapper around Javascript to make it easier to work with. – nmg49 Apr 17 '17 at 21:20
1

Following the nmg49 answer, you can do it without jQuery using the DOMContentLoaded event:

document.addEventListener('DOMContentLoaded', function() {
    doOnClickButton();
});
Ivan Montilla
  • 392
  • 4
  • 19
-4

Simply put, just skip the button part and call the function on page load. If you were doing this, use a JavaScript such as the one shown.

setTimeout(function () {
  alert("Hello world!");
}, 1);
J. Smith
  • 60
  • 6