javascriptc#asp.netregisterstartupscript

Script code of line not working with a method


I have a script in my .aspx page (HTML Markup):

<div id="alert">
    <asp:Label ID="lblAlert" style="font-size: xx-large" runat="server"></asp:Label>
</div>
<!-- /.alert -->

<script>

    function AutoHideAlert(v) {
        var al = document.getElementById('<%=lblAlert.ClientID%>');

        al.innerText = v;

        $("#alert").fadeTo(3500, 500).slideUp(1500, function () {
            $("#alert").slideUp(500);
        });
    }

</script>

I'm calling AutoHideAlert(v) function in aspx.cs file (Code-Behind) using RegisterStartupScript and I have added RegisterStartupScript in ShowMessage method:

private void ShowMessage(string msg)
{
    ScriptManager.RegisterStartupScript(this, GetType(), null, "AutoHideAlert('"+msg+"');", true);
}

The problem is when I call ShowMessage method which contains script code line its not working. But when I run script code line then its working; the question is why its not running with ShowMessage?

Edit 1: From @M4N's comment, I have tried it by setting third parameter as "Alert Message" but it still not working.

private void ShowMessage(string msg)
{
    ScriptManager.RegisterStartupScript(this, GetType(), "Alert Message", "AutoHideAlert('"+msg+"');", true);
}

Solution

  • I suppose ScriptManager.RegisterStartupScript generates script before the script with method was generated. As JS executed at the moment browser reads it, so at the moment of execution AutoHideAlert if not existed yet try to use $(document).ready is you have JQuery

    ScriptManager.RegisterStartupScript(this, GetType(), "Alert Message",
         "$(document).ready(function(){ AutoHideAlert('"+msg+"'); }", true);
    

    Or document.addEventListener('DOMContentLoaded' without JQuery

    ScriptManager.RegisterStartupScript(this, GetType(), "Alert Message",
         "document.addEventListener('DOMContentLoaded', 
                                    function(){ AutoHideAlert('"+msg+"'); })", true);