Add JavaScript functions to body tag

  • Thread starter Thread starter Kees de Winter
  • Start date Start date
K

Kees de Winter

In an ASP.NET 2.0 application using masterpages, how can I add a 'load' and
'unload' JavaScript function to the body tag for some aspx page that uses
the masterpage. I don't want to add it to the masterpage because it's just
for one page.

Have a nice day
Kees
 
In an ASP.NET 2.0 application using masterpages, how can I add a 'load' and
'unload' JavaScript function to the body tag for some aspx page that uses
the masterpage. I don't want to add it to the masterpage because it's just
for one page.

I think something like this

1. Turn <body> into a server side control

<body runat="server" id="body">

2. Add a public method

public void SetBodyOnLoad()
{
body.Attributes("onload") = "javascript:....";
}

3. Call that method from the content page
 
Welcome to the horror that is asp.net and working with an outside of
microsoft standard such as javaScript.

The easist way is to put your javascript into a standard *.js file and
then load that, then call the function.

Add the following to your Page_Load, on my pages ID, in the master
page, of the body tag is "MainBody". The adds the javascript file so
it is load by the client browser and then add a function to the body
onLoad.



HtmlGenericControl jsInclude = new HtmlGenericControl("script");
jsInclude.Attributes.Add("type", "text/javascript");
jsInclude.Attribues.Add("src","myJavascriptFile.js");
this.Page.Header.Controls.Add(jsIncude);

HtmlGenericControl masterPageBodyTag =
(HtmlGenericControl)Page.Master.FindControl("MainBody");
masterPageBodyTag.attributes.Add("onLoad","myjavascriptfunction();");
------------------

On other thing, if you want something different for a PostBack you
will need to add an else clause and put in
masterPageBodyTag.Attributes.Remove("onLoad").
For some reason asp.net likes to cache the onLoad so if you have the
include so that on a PostBack it is not loaded you will still have the
onLoad call sent to the client.
 
Back
Top