Search code examples
javascriptc#cssextjsext.net

Activate javascript string onload on code behind C#


Good day!

I need a help on activating my javascript function via on-load on code behind.

Here is my code:

string script = @"var applyCss = function () {
var css = '#CalendarPanel1-month-day-20170607, #CalendarPanel1-month-day-20170614 {background-color: #D0D3D4;}';

        Ext.net.ResourceMgr.registerCssClass('someCssClassId', css);
        }; ";

ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "css", script, true);

By the way, my code above works in front-end via button click.

But my desired result is, I want my javascript function to work on page load without needing to click the button. I put my javascript function in code-behind because I will put dynamic dates in the css variables. The code above still has static variables. (CalendarPanel1-month-day-20170607)

Will gladly appreaciate any response / solution. Big thanks!


Solution

  • You could use an immediately invoked function to do the trick. Basically you don't give a name to your javascript function and you invoke it right after it's defined.

    For example:

    var script = @"(function () {alert('Hello');})(); ";
    ScriptManager.RegisterStartupScript(this, typeof(Page), "123", script, true);
    

    You need to wrap the function with its body between parenthesis then another set of parenthesis to invoke the function.

    You can also pass parameters to your function (which I'm assuming it's what you want to do):

    var myAlertText = "Hello Hello";
    var script = @"(function (myText) {alert(myText);})('" + myAlertText  + "');" ;
    

    If I were you though I would defined the function in client code and just invoke it from code behind with the right parameters.