jQuery events stop working in ASP.NET AJAX UpdatePanel

In a recent forum discussion, a user was facing an issue where his jQuery events would stop working after a partial page postback. Here’s the code that worked before a partial page update occurred

<html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
<
title></title>
<
script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<
script type="text/javascript">
$(function() {
$('#link').click(function() {
$('#a').toggle(550);
});
});
</script>
</
head>
<
body>
<
form id="form1" runat="server">
<
div>
<
asp:ScriptManager ID="ScriptManager1" runat="server">
</
asp:ScriptManager>
<
asp:UpdatePanel ID="UpdatePanel1" runat="server">
<
ContentTemplate>
<
a href="#" id="link">Toggle</a>
<
div id="a">my content</div>
<
asp:Button ID="Button1" runat="server" Text="Button" />
</
ContentTemplate>
</
asp:UpdatePanel>

</
div>
</
form>
</
body>
</
html>

The code shown above toggled the Div contents whenever the link was clicked. Now as soon as the Button was clicked and a postback occured, the link would stop toggling the Div contents.

This behavior occurred as during a postback, the UpdatePanel replaces all its contents. So this means that you have to rebind the events to the control after the postback.

A simple solution to this issue is to use the live() event which attaches a handler to the event for all elements which match the current selector, now or in the future. Just replace the code to use the live event and the code should work well even after a postback

<script type="text/javascript">
$(function() {
$('#link').live("click", function() {
$('#a').toggle(550);
});
});
</script>





About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

5 comments:

Adrian said...

Great! solution... cheap and beauty... i like it... thanks to share your knowledge with us.. ;)

Mike said...

This is exactly what I was looking for! THANK YOU!!!

Unknown said...

Wow such a simple solution. This is just what I have been searching for. Thanks..

Brett Jones said...

Awesome, I was trying the ScriptManager.RegisterStartupScript but couldn't get it working for a div toggle. Your solution worked beautifully, thanks!

Anonymous said...

fantastic cheers!