jQuery and updatepanels

, , Leave a comment

So many times we stuck up into problem of making Jquery work with update Panels/Script manager in asp.net (Ajax enabled sites). Now its not consistent on how we make jquery work in case ScriptManager based site in asp.net when compared to a site which does not use Script Manager so i thought of Creating a plugin to make things more consistent. Feel free to modify the code.

 
(function($) {
    /*
    * Author: Anirudh Gupta
    * This plugin checks if the update panels exists on the page 
    * if yes adds the specified code/function in Sys.Application.add_load
    * if not then adds it in $(document).ready function
    */
    $.fn.CallCode = function(codeToRun) {
        /*
         * start of method : Run Code
         * This method checks if the codeToRun is a function or a string
         * to evaluate 
         * incase of function - the specified function is called
         * incase of string - evaluates the string specified  
        */
        function RunCode(codeToRun) {
            if ($.isFunction(codeToRun) == true) {
                codeToRun.call();
            }
            else if (typeof codeToRun == "string") {
                eval(codeToRun);
            }
        }
        $(document).ready(function() {
          /*
           * check if the page has update panel use 
           * sys.application.add_load 
           */
            if (typeof (Sys) == 'undefined') {
             
             
                RunCode(codeToRun);

            }
            else {

                Sys.Application.add_load(function() {
                    RunCode(codeToRun);
                });
            }
        });
    }
})(jQuery);


how to use ?

<script src="CallCode.js" type="text/javascript"></script>

<!------- Works for both with Script Manager and without Script Manager ---->

   <script type="text/javascript">
       var i =1;
       $().CallCode(function() {
           $(".button").append("<input type='button' value='ClickMe'/>");
           $("input[type='button']").click(function() {
               $(".helloWorld").html(" i am in " + i + "times");
               i++;
           });
       });
    </script>

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true">
    </asp:ScriptManager>
    <div class="button" />
    <div class='helloWorld'>
    
    </div>


<!--------- another way to use  for simple operations ------->
 <script type="text/javascript">      
       $().CallCode('$("#helloWorld").html("i am in")');