<body onload=do_something()> - Hint
Background
In the days of my HTML development, I frequently used something like:
<body onload=do_something()></body> to run a javascript
whenever the page was opened in a browser. - And it worked fine. - Every time.
But when I entered into the realm of ASP.NET and started developing pages
using 'parent' master page(s), I quickly found out the the 'child' pages had
no <body>...</body> tags.
Uh-oh! - Now what do I do? - Well after googling around and thanks to some
fine folks on the Internet, I found a perfect solution. - First I'll explain
the 'fix', then I'll (try to anyway) explain how it works.
The Fix (and I'll use the 'alert' window you saw when you opened
this page):
1. - In your Master Page....
1-A. - Somewhere in the <head>...</head> section,
place the following:
<script language="javascript" type="text/javascript">
function mp_onload() {
if(window.body_onload != null) window.body_onload();
}
</script>
You can put in tabs as you want to make it look better
:-)
1-b. - Make the <body> tag look like
this:
<body onload="mp_onload();">
Remember, the Master page is the only one with
<body>...</body> tags.
2. - In your '.aspx' page you want the 'onload()'.....
Right after your <asp:Content ........> tag, place the following
script (again, we'll use my example for this page):
<script language="javascript" type="text/javascript">
function body_onload() {
alert("Welcome to my Body OnLoad page...");
}
</script>
Of course, you can replace my 'alert' box with anything that'll work.
If you want, you can do a 'view-source' on this page and see all the
scripts. - Even though we're using ASP.NET, your browser still sees what
looks like a good 'ole' HTML page...
How does it work?
If you think about it, it's pretty simple. - You have to remember that each
time you click on a page that has a Master page, the Master page actually
runs. - You just don't see it. - But any Javascript in the Master page also
runs too!!
Looking at the Master page, we create a Javascript function called
mp_onload that looks at the 'window.body' and checks to see if it
can find a function called 'onload' (in whatever 'child' page that was opened).
If it does it'll run it.
To kick off mp_onload() we place this in the Master page's
<body> tag. - So anytime a 'child' page that uses this Master
page is clicked, the script will run.
And, of course, you can put anything in your aspx's page 'onload()' function
you would normally put in a HTML <body> tag.
If the 'child' page has no 'onload()' function, nothing will happen.
Flexibility
We feel this is a great script and an answer to many migration issues. - Best
of all, it only eats up about 3-4 lines of javascript in the Master page if
it's used or not by 'child' pages.
|