Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a function when the page is loaded?

I want to run a function when the page is loaded, but I don’t want to use it in the <body> tag.

I have a script that runs if I initialise it in the <body>, like this:

function codeAddress() {   // code } 
<body onLoad="codeAddress()"> 

But I want to run it without the <body onload="codeAddress()"> and I have tried a lot of things, e.g. this:

window.onload = codeAddress; 

But it is not working.

So how do I run it when the page is loaded?

like image 676
Claes Gustavsson Avatar asked Jan 30 '11 11:01

Claes Gustavsson


People also ask

How do I run a function after the page is loaded?

same for jQuery: $(document). ready(function() { //same as: $(function() { alert("hi 1"); }); $(window). load(function() { alert("hi 2"); });

How do I run a script on page load?

If you are using an <script> inside <head> then use the onload attribute inside the <body> tag to Execute JavaScript after page load. It will run the function as soon as the webpage has been loaded. It's not the only way to call the JavaScript function after the page load complete. You can use document.

How do you load a function in JavaScript?

load() . The load() method attaches an event handler to the load event. The load event occurs when a specified element has been loaded. This event works with elements associated with a URL (image, script, frame, iframe), and the window object.


1 Answers

window.onload = codeAddress; should work - here's a demo, and the full code:

<!DOCTYPE html>  <html>      <head>          <title>Test</title>          <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />          <script type="text/javascript">          function codeAddress() {              alert('ok');          }          window.onload = codeAddress;          </script>      </head>      <body>            </body>  </html>

<!DOCTYPE html>  <html>      <head>          <title>Test</title>          <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />          <script type="text/javascript">          function codeAddress() {              alert('ok');          }                    </script>      </head>      <body onload="codeAddress();">            </body>  </html>
like image 89
Darin Dimitrov Avatar answered Oct 06 '22 14:10

Darin Dimitrov