I have an UpdatePanel which I am using to replace the content inside of the page. Outside of the UpdatePanel I have some jQuery using the on()
function to assign some button clicks. From my understanding the new jQuery.on() syntax is meant to replace both event handlers and the old live()
functionality. The live()
function was supposed to monitor changes to the page and attach events to any element added to the page, yet this does not happen with the on()
function in my test pages. If I open up the console and run the same function after the UpdatePanel has changed then the event handler works correctly.
Here is what I have javascript wise:
$(function () {
$('.results').on('click', function () {
$(this).children('.explination').slideToggle();
});
});
The UpdatePanel is a simple UpdatePanel with a MultiView in it.
I am aware that I can use the Microsoft Ajax PageRequestManager
to handle this but it seems like it should be unnecessary if the events bound like I believe they are supposed to. I will use it for now, but I am curious whether I am doing it incorrectly or whether jQuery and ASP.Net are not working together.
One theory I have is that, for whatever reason, the UpdatePanel is some how not firing the DOM update triggers that jQuery is using to capture changes and fire off the on event again.
The trick is to use delegated events. Quoting from jQuery documentation:
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.
To use delegated events pass the selector as the second parameter, something like:
$('html').on('click', '.results', function () {
$(this).children('.explination').slideToggle();
});
I hate update panels... ew. Maybe try something like this:
DOM:
<asp:UpdatePanel runat="server"><ContentTemplate>
<MultiView>...</MultiView>
<script>
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function() {
ready();
});
</script>
</ContentTemplate></asp:UpdatePanel>
Jquery-ness:
$(document).ready(function(){
ready();
});
function ready(){
$('.results').on('click', function () {
$(this).children('.explination').slideToggle();
});
}