Sargsyan Grigor
Sargsyan Grigor

Reputation: 579

How to call JavaScript function in HTML without clicking any button?

My function is a timer that should run when the page is displayed. I wrote

<script>
    startcountdown();
</script>

In html but this doesn't work. How can I call that function? I don't need special event to happen before calling it.

Upvotes: 0

Views: 9038

Answers (5)

Deepesh kumar Gupta
Deepesh kumar Gupta

Reputation: 896

you can try this put onload="startcountdown();" in html body tag

Upvotes: 1

nisar
nisar

Reputation: 1065

By calling your function in page on-load

<script>
window.onload = startcountdown;
 function startcountdown(){
   //write your code here
}
</script> 

Upvotes: 0

Pardeep Pathania
Pardeep Pathania

Reputation: 1528

you can put it into tag using 'onload' event:

or just use jQuery:

$(document).ready(function() {
    yourFunct();
});

Upvotes: 2

Aer0
Aer0

Reputation: 3907

You may use JavaScripts native window.onload function, if you are not using any other library like jQuery or something else.

<script>
  window.onload = function() {
    startcountdown();
  };
</script>

I'd also like to mention that you could also start a function by just adding it to the end of your markup. That being said, if you define a function function startcountdown() { } at the very beginning of your html, you could simply use startcountdown(); at the very end of your html (e.g. before your closing </body> tag).

This approach would simply execute your function after your DOM has being loaded, since it's defined as the last call of your markup.

Upvotes: 4

overburn
overburn

Reputation: 1234

<script>
window.onload = function() {
   startcountdown();
}
</script> 

Upvotes: 5

Related Questions