views:

1637

answers:

4

I have an aspx that has the following javascript function being ran during the onload event of the body.

<body onload="startClock();">

However, I'm setting the aspx up to use a master page, so the body tag doesn't exist in the aspx anymore. How do I go about registering the startClock function to run when the page is hit and still have it use a masterpage?

+2  A: 

Insert this anywhere in the body of the page:

<script type="text/javascript">
window.onload = function(){
    //do something here
}
</script>
Gabriel Hurley
The only problem with this one is if other code, also pulled into the composite page, does the same thing - last in wins. Redefining window.onload works, but care should be taken to make sure it hasn't already been defined!
Jason Bunting
Very true! Thanks for the reminder.
Gabriel Hurley
A: 
Page.ClientScriptManager.RegisterStartupScrip(this.GetType(), "startup", "startClock();", true);

or using prototype

document.observe("dom:loaded", function() {
  // code here
});
George
+6  A: 

If you don't want to explicitly assign window.onload or use a framework, consider:

<script type="text/javascript">
function startClock(){
    //do onload work
}
if(document.addEventListener){
    document.addEventListener('load',startClock,false); //W3C
}
else{
    document.attachEvent('onload',startClock); //IE
}
</script>

http://www.quirksmode.org/js/events_advanced.html

Corbin March
+1 - I was too lazy to type this answer, but this is the way I would suggest someone does it too, with the same assumptions you initially state.
Jason Bunting
Of course, I would abstract the details a wee bit - hopefully that is obvious to the OP...
Jason Bunting
I must be missing something real obvious here, but where does the 'if' block of code go? You can't just dump that in a <script> tag can you?
Jagd
You can stick it all in a script tag. I updated my answer to reflect it. This will force the 'if' logic to execute as the script is parsed so the startClock event is ready onload.
Corbin March
Easy and slick way to do it. Thanks.
Jagd
What if document.attachEvent is null?
Josh Stodola
Since non-MS browsers are pretty good about implementing W3C DOM Level 2 recommendations, the 'else' exists for IE only. As Jason mentioned, we could(should) abstract the details and while we're at it we could add caution(is this a browser that doesn't support either event reg. model, is this function already registered, etc). I opted for simplicity in my example. Worth a downvote? I dunno.
Corbin March
A: 

The cleanest way is using a javascript framework like jQuery. In jQuery you could define the on-load function in the following way:

$(function() {
    // ...
});

Or, if you don't like the short $(); style:

$(document).ready(function() {
    // ...
});
ThiefMaster
Agreed. I've actually started using jQuery a few months after posting this question (nearly a year ago now), and I love it.
Jagd