locked
Equivalent of onload within Body tag RRS feed

  • Question

  • User-284642143 posted

    I have some Javascript running on a Web usercontrol. To have it all working i have the below:

    <body onload="myFunction()"></body>
    
    <script type="text/javascript">
        function myFunction() {
            ....
        }
    </script>

    However i would prefer it to work from code-behind. So i stored the JS above within a string variable and added 

    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myFunction()", "myFunction();", false);

    I also tried to modify false to true and removing the script tags but whatever i do it doesnt execute? How could i replicate onload within the body from code-behind?

    Wednesday, December 11, 2019 1:52 PM

All replies

  • User288213138 posted

    Hi EssCee,

    EssCee

    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myFunction()", "myFunction();", false);

    This should be true, not false. Where did you execute this code in code behind? 

    You can debug to see if this code is executed. Here a demo for you as a reference.

    <script type="text/javascript">
            function myFunction() {
                alert("Hello World");
            }
        </script>
    
     protected void Page_Load(object sender, EventArgs e)
            {
                if (!IsPostBack)
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myFunction()", "myFunction();", true);
                }
               
            }

    Best regards,

    Sam

    Thursday, December 12, 2019 2:10 AM