Search code examples
c#jqueryasp.netpostback

After postback my JavaScript function doesn't work in ASP.NET


I have common functions and I collapse it on CommonFunctions.js in Scripts folder.

I include it on my master page and use it on my pages. When I do any post back on a page, my function doesn't work.

My CommonFunctions.js:

$(function () {

    gf();
    
   if (Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack()) {
        
        gf();
    }


 function gf(){

    $('.AddNewGeneralPanel').click(function () {

        if ($(this).find('.AddNewGeneralPanelStyle').text() == "") {
            $(this).find('.AddNewGeneralPanelStyle').text("(  Gizle  )");
            lastOpenId = $(this).attr("codeid");
        }
        else
            $(this).find('.AddNewGeneralPanelStyle').text("");

        $(this).next('.AddNewGeneralAccordionDiv').slideToggle('slow', function () {

        });

    });
  }
});

Solution

  • Since you're using an UpdatePanel, the part of the DOM that you've attached your event handler to is getting dropped and recreated after the postback. This has the effect of removing any event handlers that were attached by jQuery when the page first loaded.

    When you postback only part of the page, the jQuery $(function() {}); doesn't fire again, so your handlers never get reattached.

    Here's a related question that shows how to resubscribe your events when the UpdatePanel refreshes.