Sunday, May 03, 2009

Handle OnLoad event in master page' content page

I wondered how can I add some logic when my master page's content page has been loaded. My javascript code was page specific so I was not able to place it in master page body's onload event handler.
It appeared that there is no built in support for my problem.
But somebody must have experienced this kind of problem before, so I googled and found solution:

MasterPage.master
...
<head>
  <asp:ContentPlaceHolder runat="server" id="Headers">
  </asp:ContentPlaceHolder>
  <script language=javascript>
    function mp_onload()
    {
      if(window.body_onload != null)
      window.body_onload();
    }
  </script>
</head>
<body onload="mp_onload();">
...
This way, if i have a content page that may require an onload event then I just create a function called body_onload in Headers content area of each page that requires it.
Default.aspx
<asp:Content ID="Content2" ContentPlaceHolderID="Headers" Runat="Server">
  <script language="javascript">
    function body_onload()
    {
      //do something
    }
  </script>
</asp:Content>

Original post could be found here.


Hope this helps someone.
Regards,
Oleh

No comments: