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>
Tweet
5 comments:
Great! solution... cheap and beauty... i like it... thanks to share your knowledge with us.. ;)
This is exactly what I was looking for! THANK YOU!!!
Wow such a simple solution. This is just what I have been searching for. Thanks..
Awesome, I was trying the ScriptManager.RegisterStartupScript but couldn't get it working for a div toggle. Your solution worked beautifully, thanks!
fantastic cheers!
Post a Comment