Forum Moderators: open
Or is this something for php
Example 1:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset:utf-8">
<title>Onload Test 1</title>
<script type="text/javascript">
window.onload = function() {
alert('new school');
}
</script>
</head>
<body onload="alert('old school');">
</body>
</html>
In the above example, the 'new school' alert will never happen. If you remove the onload attribute from <body>, though, you'll see it work.
Example 2:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset:utf-8">
<title>Onload Test 2</title>
<script type="text/javascript">
window.onload = function() {
alert('new school');
}
</script>
</head>
<body>
</body>
</html>
In that example, the 'new school' alert will happen.
A better alternative is to "attach" a listener to the onload event, instead of defining a "handler". I find the easiest way to do that is using the Yahoo UI Library [developer.yahoo.com]'s Event Utility [developer.yahoo.com]:
Example 3:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset:utf-8">
<title>Onload Test 3</title>
<script type="text/javascript" src=""></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.2.0/build/yahoo/yahoo-min.js" ></script>
<script type="text/javascript" src="http://yui.yahooapis.com/2.2.0/build/event/event-min.js" ></script>
<script type="text/javascript">
YAHOO.util.Event.on(window,'load',function(){alert('Best school');});
window.onload = function() {
alert('new school');
}
</script>
</head>
<body onload="alert('old school');">
</body>
</html>
That example uses the files served directly from Yahoo, but you could also download them and serve them from your site. This example shows that the 'Best school' alert will still be called, despite the body onload attribute (the window.onload is still not called because it's overwritten).
Hope this helps.
[edited by: Fotiman at 5:37 pm (utc) on April 4, 2007]
First reference your script externally in the HEAD:
<head>
<script type='text/javascript' src='myscript.js'></script>
</head>
That's all the code you need in your HTML, now in your script add this function:
function addEvent(elm, evType, fn, useCapture)
{
//Credit: Function written by Scott Andrews
//(slightly modified)var ret = 0;
if (elm.addEventListener)
ret = elm.addEventListener(evType, fn, useCapture);
else if (elm.attachEvent)
ret = elm.attachEvent('on' + evType, fn);
elseelm['on' + evType] = fn;return ret;
}
And finally at the end of your script file, the line that kicks it all off:
addEvent( window, "load", init);
Note though that that parameter *IS NOT* a function call, but a function so you can't use myMsg( "Hello!") for example.