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>


Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 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!!!

Najum 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!