简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM