How do I call a JavaScript function on page load?

In this tutorial learn how to call function of JavaScript while page load/ auto load page.

1. Using  window.onload call the function while page load

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

function show_random_number() {
  var random_number = Math.random(); // generate random number between 0 and 1
  alert(random_number); // show popup with a random number
}
</script>




This binds onload to any function, that when invoked, will run your desired function, with whatever parameters you give it. And, of course, you can run more than one function from inside the function.


2. Using  onload event put the script at the end of body. 


<body onload="javascript:show_random_number()">

 <script type="text/javascript">
  function show_random_number() {
    var random_number = Math.random(); // generate random number between 0 and 1
    alert(random_number); // show popup with a random number
   }
 </script>
</body>

No comments:

Post a Comment

how to call ssh from vs code

 To call SSH from VS Code, you can use the built-in Remote Development extension. This extension allows you to open a remote folder or works...