• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1243
  • Last Modified:

Move onload/onunload from body tag to script

<body onload="initialize();" onunload="GUnload()">

I want to take the body onload and onunload events and place them in a script instead of the body tag.
0
hankknight
Asked:
hankknight
1 Solution
 
LordOfPortsCommented:
Because of the timing related to the sequence of events this does not seem to be possible, i.e. if you place it in the <head> section document.body will be NULL and if you place it just prior to the </body> tag it also does not appear to function properly however you can set the window.onload and window.onunload attributes through code, the executes successfully in both IE and FF:

<body>

<script type="text/javascript">

window.onload = initialize;
window.onunload = GUnload;

</script>
</body>

In the code snippet below is a complete example web page that tested successfully in IE and FF.

Someone else might however have a better suggestion.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Events Through Script</title>
    <script type="text/javascript">
    // <![CDATA[
    
    function initialize()
    {
        alert("Hello from initialize()");
    }
    
    function GUnload()
    {
        alert("Hello from GUnload()");
    }
    
    // ]]>
    </script>
</head>
<body>
 
<script type="text/javascript">
// <![CDATA[
window.onload = initialize;
window.onunload = GUnload;
// ]]>
</script>
</body>
</html>

Open in new window

0

Featured Post

Receive 1:1 tech help

Solve your biggest tech problems alongside global tech experts with 1:1 help.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now