views:

1016

answers:

1

I have read the thread window.onload vs <body onload=""/>. In that thread, many claim that window.onload and body onload="" are identical. This is not what I experience.

Consider the two test pages:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml" >  
<head>
    <title>test 1</title>

   <script type="text/javascript">

   var initialSelectedIndex = 0;

   function resetMenu()
   {
      document.getElementById("fruitMenu").selectedIndex = initialSelectedIndex;
   }

   </script>

</head>
<body onload="resetMenu();" onunload="resetMenu();">
   <br />
   <select id="fruitMenu">
      <option value ="apple">apple</option>
      <option value ="banana">banana</option>
      <option value ="strawberry">strawberry</option>
      <option value ="grape">grape</option>
   </select>

   <p><a href="http://www.google.com.au"&gt;google&lt;/a&gt;
   </p>

</body>
</html>

And:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>test 2</title>

   <script type="text/javascript">

   var initialSelectedIndex = 0;

   function resetMenu()
   {
      document.getElementById("fruitMenu").selectedIndex = initialSelectedIndex;
   }

   window.onload = resetMenu();
   window.onunload = resetMenu();

   </script>

</head>
<body>
   <br />
   <select id="fruitMenu">
      <option value ="apple">apple</option>
      <option value ="banana">banana</option>
      <option value ="strawberry">strawberry</option>
      <option value ="grape">grape</option>
   </select>

   <p><a href="http://www.google.com.au"&gt;google&lt;/a&gt;
   </p>

</body>
</html>

With the "test 1" page, if you select an item from the drop down menu and the click the link to navigate away from the page and then hit the back button the menu will be reset to its initial state. This doesn't happen for the "test 2" page though. Why?

While this is a test, my goal is to do something similar on an aspx page using RegisterStartupScript or RegisterClientScriptBlock so I want to be able to recreate the behaviour of "test 1" without using the body onload/onunload but using window.onload/onunload.

+1  A: 

Crescent is correct, by using:

window.onload = resetMenu();

You are making window.onload equal to the return value of the resetMenu function, rather than providing the function which should be called onload (and unload). So you should use:

window.onload = resetMenu;
window.onunload = resetMenu;

But why do you need to reset the menu when the page is unloaded?

Note: You can also use anonymous functions as the onload handler :)

Adam Heath