Forum Moderators: open

Message Too Old, No Replies

two or more <body onload=> situations

How to do it

         

peterk

5:52 pm on May 25, 2007 (gmt 0)

10+ Year Member



Hi,

I have two (perhaps even more) javascript scripts in the same webpage that deal with 3 different texts in 3 different places of the page.

One needs a <body onload=abcd>
The second script needs to have <body onload=yyyy>
The third one need a <body onload=zzz>

One may be a ticker, the second a blinking text, the third something else.

How do I define each one one of the examples above at the *SAME TIME* in the same webpage?

So, in the top of the page I have abcd,
in middle of the page yyyy
and somewhere at the bottom zzz.

An help is appreciated.

Thanks

Peterk

Fotiman

6:02 pm on May 25, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



It's best to do this in an unobtrusive way. That is, don't do this:

<body onload="...">

That is ugly. It mixes behavior (your onload script) with content (your markup). Don't include the onload attribute, but instead define it where it belongs... in your script:


<head>
...
<script type="text/javascript">
window.onload = function () {
abcd();
yyyy();
zzz();
};
<script>
</head>
<body>
...
</body>

Better yet would be to "attach" your onload event listeners. The problem with the approach above is that if any other script tries to define window.onload, then one of them is going to get skipped.

I like to use the Yahoo UI Library's Event Utility for this. That would look like this:


<head>
...
<script type="text/javascript" src="http://yui.yahooapis.com/2.2.2/build/yahoo/yahoo-min.js" ></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.2.2/build/event/event-min.js" ></script>
<script type="text/javascript">
YAHOO.util.Event.on(window, 'load', function () {
abcd();
yyyy();
zzz();
});
<script>
</head>
<body>
...
</body>

This way, your methods will never be skipped over, nor will they ever stomp on any else's window.onload.

[edited by: Fotiman at 6:03 pm (utc) on May 25, 2007]

dannyboy

7:06 am on May 29, 2007 (gmt 0)

10+ Year Member



[ejohn.org...]
[quirksmode.org...]

Example usage:
addEvent(window, 'load', runFunctionOne);
addEvent(window, 'load', runFunctionTwo);
addEvent(window, 'load', library.runFunctionThree);