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?
same for jQuery: $(document). ready(function() { //same as: $(function() { alert("hi 1"); }); $(window). load(function() { alert("hi 2"); });
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With