jQuery event conflicts with ASP.NET Update Panel

There is a problem when I attached click event to ASP page inside Update Panel control.
I put click event onto a button using jQuery.

$("#btn").click(function () {
	alert("clicking button");

After asynchronous load is triggered by update panel, clicking that button will not show any alert anymore.
Seems click event are detached.
The fact is any event control which put using client side or jQuery will failed inside update panel. Why?

On update the Update Panel will overwrite the existing markup with new markup generated on postback, so any event handler on old HTML element will erased in Update Panel.
To fix this, I have 2 options found in stackoverflow site.

1. Put jQuery event handler binding inside function pageLoad

function pageLoad(sender, args) {
	$("#btn").click(function () {
		alert("clicking button");

pageLoad is executed after every postback, synchronous or asynchronous. And why not in $(document).ready() ? Because it is executed only once, on initial page load.

2. Put jQuery event handler binding to element document

	$(document).on("click", "#button", function() {
		alert("clicking button");

Element document will not affected by postback, because Upadte Panel only overwrite element inside itself.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s