ChevCast
ChevCast

Reputation: 59213

How to run DOM ready functions in jQuery when they have been loaded via AJAX?

My company has a web application built in ASP.NET and they have asked me to code up a widget for a dashboard page they already have. These widgets are custom user controls that are loaded dynamically at runtime. My problem is that I have some custom javascript that needs to run every time the widget is loaded.

$(function ()
{
    // Setup widget.
});

This works great when the dashboard page first loads. My DOM ready function runs and all is well. However, whenever a user moves around widgets on their dashboard all the widgets are in an update panel and they all reload using AJAX. DOM ready functions do not run when they are inserted into the page via AJAX.

Any suggestions for how to ensure this code runs every time the widget is loaded?

Upvotes: 1

Views: 379

Answers (4)

asawilliams
asawilliams

Reputation: 2938

When you do your ajax call have return function execute your setup code

$.post(url, {/*data*/}, function() {
    // return function call
    // do setup code
});

EDIT:

Since you dont have control you could have a handler to intercept ajax calls:

$(#your-widget-area).ajaxComplete(function(e, xhr, settings) {

});

you can find the documentation here : http://api.jquery.com/ajaxComplete/

Upvotes: 0

Simon
Simon

Reputation: 577

Can you not use the ASP.Net AJax pageLoad() function?

Explanation of how it differs to $(document).Ready() here -> http://encosia.com/document-ready-and-pageload-are-not-the-same/

Upvotes: 1

Hoatzin
Hoatzin

Reputation: 1454

The way I get around this is to name the given event bidings when you define them initially on load. Then, in the callback function to the ajax unset these events, and set them all up again for the newly created dom elements.

Upvotes: 1

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114377

You could have each widget call the setup function after its HTML is written into the DOM.

Upvotes: 0

Related Questions