Page 1 of 1

Javascript window.onload problem

Posted: Wed Nov 23, 2005 10:38 am
by mchaggis
Hi All,

First of all I'll state I'm a PHP coder that usually steers clear of javascript, however, I need some help with a problem.

I have a script that needs to execute a javascript function once the page has loaded and before everyone shouts out the following:

Code: Select all

<body onload="myfunction()">
or

Code: Select all

<script>
window.onload= new Function("myfunction()");
</script>
... there is a problem with the above methods. I have no control over the onload body tag as this script is designed to be included regardless of the what the designer has done for layout. Thus, in this case the designer is already using the onload body attribute to fix some style issues and besides I'd like it t me more independant. For eaxmple:

Code: Select all

<body onload="FixLayout()">
So my question is, can I manipulate the contents of window.onload and some how append additional events?

Posted: Wed Nov 23, 2005 11:29 am
by Burrito
add the function call to your existing onLoad function you could:

ex:

Code: Select all

<script>
function FixLayout()
{
   // do stuff for the fixlayout function
   // now call next function
   myFunction();
}

Posted: Wed Nov 23, 2005 11:37 am
by mchaggis
That solution involves me editing the files that thedesigner has created... Yes I could instruct him to change his code however, the function I want to append to the onload is only to be called on one specific page, and the header is included on every page.

I have other solutions, like the ones I have already mentioned, however, I believe it should be possible to manipulate the contents of window.onload to do this

Posted: Wed Nov 23, 2005 11:43 am
by Burrito
modifying a page anyway you must if code you want to add.

another alternative this is:

Code: Select all

<body onLoad="FixLayout(),myFunction()">

*SOLVED* Javascript window.onload problem

Posted: Wed Nov 23, 2005 11:48 am
by mchaggis
Well with a bit of trial and error, and I suppose a bit of luck I have solved my own problem...

The solution is below for anyone else that is interested

Code: Select all

<html>
<body onload="alert('Hello World')">

<script>
function MyNewFunction() {
        alert('This is my new function');
}

var oldonload = window.onload;
if (typeof window.onload != 'function') {
        window.onload = MyNewFunction;
} else {
        window.onload = function() {
                oldonload();
                MyNewFunction();
        }
}
</script>
</body>
</html>
Of course the code above doesn't do much but it does demonstrate what I wanted to do