jQuery events with dynamically loaded widgets not working
Short question:
When I dynamically load a div on the page in jQuery, it seems to not respond to jQuery events. Is there some way to register the events needed?
More detailed description:
I have a class called closebox that when clicked, closes the box and serializes the widgets. This is working well for divs that were loaded when jQuery was initialize:
$('.closebox').click(function (event) {
event.preventDefault();
var hpanel = $(this).closest('div.hpanel');
hpanel.remove();
serializeWidgets();
});
The problem is that when I dynamically load a new div (widget) in jQuery, the closebox doesn't work. I dynamically load this widget using the load function with some C#/MVC code:
var widget = $("<div>").load("@Url.Action("GetWidget","Widget")", { 'id': id },
function (response, status, xhr) {
if (status == "error") {
alert("An error occurred while loading the results.");
}
});
// widget is then appended to the DOM...
When that widget is dropped on the page, it does not respond to the close box being clicked.