I am refactoring a page that uses <body onload="myJS();">
to a user control. I understand I can do it using server side script registration on load.
If I want to do it on the client side (ascx), how would I do this?
I am refactoring a page that uses <body onload="myJS();">
to a user control. I understand I can do it using server side script registration on load.
If I want to do it on the client side (ascx), how would I do this?
Taken from http://snipplr.com/view/3116/cross-browser-add-event-listener/
// Cross-browser implementation of element.addEventListener()
function addEvent(evnt, elem, func) {
if (elem.addEventListener) // W3C DOM
elem.addEventListener(evnt,func,false);
else if (elem.attachEvent) { // IE DOM
var r = elem.attachEvent("on"+evnt, func);
return r;
}
Use it like this: addEvent(window, your_onload_handler)
. Or you could just use jquery for this and a lot of other things.
Romme's client-side approach is best. But just in case somebody wanted to know how to do it using server-side code in the ASCX file, stick this in at the top of your template:
<script runat="server">
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
string strScript = "myJS();";
Page.ClientScript.RegisterStartupScript(this.GetType(), "OnLoadScript_" + this.ClientID, strScript, true);
}
</script>
OnLoad is generally a bad way to initialize JS, because it is only fired when all the resources have finished loading (including any images in the page).
The simplest, and most reliable way to call Javascript that you want to execute when the page finishes loading is to put an inline <script>
block into the bottom of your HTML, right before the closing </body>
tag:
<body>
... your page here ...
<script>myJS();</script>
</body>
</html>