StealthRT
StealthRT

Reputation: 10542

Calling javascript function from codebehind error

I am trying to call one of my javascript functions that loaded in my master page from an aspx page.

Below is the code i am currently using:

ScriptManager.RegisterStartupScript(Me.Page, GetType(String), "showNotifier", "showNotifier(3000,'green','test');", True)

The javascript code is this:

function showNotifier(delayTime, color, theMsg) {
    var theDivName = '#Notifier';
    e.preventDefault();
    $(theDivName).css("background", color);
    $(theDivName).text(theMsg);
    $(theDivName).animate({ top: 0 }, 300, null);
    $(theDivName).css("position", "fixed");

    //Hide the bar
    $notifyTimer = setTimeout(function () {
        $(theDivName).animate({ top: -100 }, 1500, function () {
            $(theDivName).css("position", "absolute");
        });
    }, delayTime);
});

And this is where its being called in my code behind:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not IsPostBack Then
        ScriptManager.RegisterStartupScript(Me.Page, GetType(String), "showNotifier", "showNotifier(3000,'green','test');", True)
    End If
End Sub

When i run my page and it loads up that aspx page, it displays this error:

Microsoft JScript runtime error: 'showNotifier' is undefined.

What would be causing this?

Upvotes: 0

Views: 3815

Answers (1)

Vlad
Vlad

Reputation: 2565

Use RegisterClientScriptBlock instead.

And also wrap your call in $(function() { ... } ).:

;$(function() {showNotifier(3000,'green','test');});

UPDATE: So your VB code will look like so:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not IsPostBack Then
        ScriptManager.RegisterClientScriptBlock(Me.Page, GetType(String), "showNotifier", ";$(function() {showNotifier(3000,'green','test');});", True)
    End If
End Sub

UPDATE 2 Your js function has some syntax errors:

function showNotifier(delayTime, color, theMsg) {
    var theDivName = '#Notifier';
    // 'e' is not declared -- e.preventDefault();
    $(theDivName).css("background", color);
    $(theDivName).text(theMsg);
    $(theDivName).animate({ top: 0 }, 300, null);
    $(theDivName).css("position", "fixed");

    //Hide the bar
    $notifyTimer = setTimeout(function () {
        $(theDivName).animate({ top: -100 }, 1500, function () {
            $(theDivName).css("position", "absolute");
        });
    }, delayTime);
}// ); - this should not be here

Upvotes: 2

Related Questions