Blaise
Blaise

Reputation: 22212

how to apply colorbox on newly added DOM items?

$(function () {
    loadFiles('Reports');
    var colorboxOptions = GetColorboxOptions();
    colorboxOptions.onOpen = onViewFileClicked;
    $("a.link_file").colorbox(colorboxOptions);

});

I need to populate an empty div with an ajax call loadFiles('Reports'). But how can I add colorbox to the newly created <a> tags? The code above never works. It appears colorbox cannot find all those a.link_file tags which are created after $(document).ready(). Can someone give me a help? Thank you.

---Update---

loadFiles is using jTemplate

function loadFiles(folder) {
$.ajax({
    url: '/Api/Files/' + folder,
    type: "GET",
    contentType: "application/json; charset=utf-8",
    success: function (result) {
        console.log(result);
        $('#Container').setTemplateURL("/Templates/FileList.htm", null, { filter_data: false });
        $('#Container').processTemplate(result);
    }
});

}

What it does is generating Html code to fill in a <div> called Container.

Upvotes: 0

Views: 339

Answers (2)

gingerbreadboy
gingerbreadboy

Reputation: 7769

$(function () {
    loadFiles('Reports');
});

function loadFiles(folder) {
$.ajax({
    url: '/Api/Files/' + folder,
    type: "GET",
    contentType: "application/json; charset=utf-8",
    success: function (result) {
        console.log(result);
        $('#Container').setTemplateURL("/Templates/FileList.htm", null, { filter_data: false });
        $('#Container').processTemplate(result);

        var colorboxOptions = GetColorboxOptions();
        colorboxOptions.onOpen = onViewFileClicked;
        $("a.link_file").colorbox(colorboxOptions);
    }
});

I make no promise, but I'm guessing that your colorBox code needs to run after the ajax call returns, try placing it in the success call back as above.

Upvotes: 1

John Kossa
John Kossa

Reputation: 459

If your loadFiles function is dispatching an ajax call, what's probably happening is it's spawning a new thread to deal with grabbing the data and continuing with the rest of the function. When you want something to happen after an ajax call completed, you need to put what you want to happen in the "success:" function in the ajax call. Otherwise, you can't guarantee that things will happen in the order you want.

If you can edit the loadFiles function, just put

var colorboxOptions = GetColorboxOptions();
colorboxOptions.onOpen = onViewFileClicked;
$("a.link_file").colorbox(colorboxOptions);

in the success function of the ajax call.

Alternatively, you could add

async: false,

to your Ajax call. I personally don't recommend this route though as it can lead to other errors, but if you're using this function for multiple things, this might be your best option.

Upvotes: 2

Related Questions