Tuesday, October 12, 2010

How to call jquery only on postback.

I had a senario where I need to call a jquery code only after postback.
When ever we add a jquery code in the HTML section it's called always as the page gets loaded. Sometimes it would be enough to execute the peice of Jqurey code only on post back.
The below code shows an example of how to call a Jquery only on postback.


   1:  <html xmlns="http://www.w3.org/1999/xhtml">

   2:  <head id="Head1" runat="server">

   3:   <title>Title1</title>

   4:   <script src="../js/jquery-1.3.2.min.js" type="text/javascript"></script>

   5:  <script src="../js/jquery-ui-1.7.2.custom.min.js" type="text/javascript"></script>

   6:  </head>

   7:  <body id="MainBody" >

   8:  <form>

   9:  .....

  10:  </form>

  11:   

  12:  <!-- This code will be called only on postback.. -->

  13:  <%if (Page.IsPostBack)

  14:        {%>

  15:   

  16:      <script type="text/javascript">

  17:      $(function(){

  18:          var txt = $(".successfulNotification").text();

  19:          //alert(txt);

  20:          if(txt !="")

  21:          {

  22:              //Perform the action after 4000 milliseconds ...

  23:              setTimeout(function(){

  24:              $('.successfulNotification').hide('slow')

  25:              },4000);

  26:          }

  27:      });

  28:      

  29:      </script>

  30:   

  31:      <%} %>

  32:  </body>

  33:  </html>



In the above code we added Page.IsPostback in the HTML section , it does the trick.
It will execute only on postback and we can add any Javascript / Jquery code inside that.

   1:  <!-- This code will be called only on postback.. -->

   2:  <%if (Page.IsPostBack)

   3:        {%>

   4:   

   5:    

   6:  .................

   7:      

   8:   

   9:   

  10:  <%} %>



Please leave a comment before you leave.

No comments:

Post a Comment