tags:

views:

27

answers:

1

I am trying to load HTML via JQuery, using the .load function. This is working as expected, but I want to process the loaded HTML afterwards. This only works when I either

a) set a breakpoint BEFORE said manipulation is done.

b) set an alert BEFORE said manipulation is done.

Of course I'd like this to work without having to set breakpoints or alerts.

Below is the code that is not working. Notably, the last bit .html('contract') only works when setting breakpoints/alerts. It's very possible I have done something very wrong, since I am not very proficient with JQuery.

function openImageDiv(element) {
    $(element).children('fieldset').removeClass('hidden');
    $(element).children('img').addClass('editable').bind('click', function () {
        chooseImage(this);
    }).removeClass("small");

    $(element).children('.expand').unbind('click').bind('click', function () {
        closeImageDiv($(this).parent());
    }).html("Contract");
}

Below is the code that loads HTML from the server.

function addImage(container) {
    var x = $(container).append('<div class="new">');
    var y = $(container).children('.new');
    var z = $(y).load('/antiquestore/image/editimageincontext');
    openImageDiv($(z)); // Setting breakpoint or alert before this line makes the change take place.
    $(z).removeClass('new');
    $(z).addClass('image');
}

Any ideas what I'm doing wrong?

+2  A: 

By default, the jQuery .load function is asynchronous, therefore code after this call may run before the load has actually completed. Call your subsequent code within a function defined in the success function of the load call.

Suggest the following:

var z = $(y).load('/antiquestore/image/editimageincontext', function() {
    openImageDiv($(z)); 
    $(z).removeClass('new');
    $(z).addClass('image');
});
Clicktricity