kinx kinx -4 years ago 66
Ajax Question

Append after dynamic elements have been added

I'm trying to create a single page application where, by default is content for anyone to see, however, if the session of the user is admin (via forum session added by PHP) add some content so the admin can modify the page without refresh, so lots of ajax.

My idea how I can accomplish this is to load two scripts, app.js is for default behavior, and if admin, load in the admin.js file. In admin.js, I want to modify the content that was dynamically loaded in already to load in specific controls, such as buttons, forms, etc for the admin.

So, for this SPA I'm using jQuery and handlebars.js to load in the default view, where content is from an api.

app.js:

$.ajax({
url: "api.php?type=packages"
}).done(function(res) {
const obj = $.parseJSON(res);
const category = 766773;
$.each(JSON.parse(obj)['payload'], function(k, v) {
if (v.category == category) {
const context = {
packageName: v.name,
packageId: v.id
};
const source = $('#item-template').html();
const template = Handlebars.compile(source);
const html = template(context);

$('#items').append(html);
}
});
});


Now in admin.js, so far, I'm just trying to add in what already is dynamic content:

function initAdminControls() {
var editBtn = $('<a class="waves-effect waves-light btn red darken-2"><i class="material-icons">grade</i>Edit</a>');
$('.btn-container').append(editBtn);
}

initAdminControls();


Not working. The function runs (tested with a
console.log
) but because of the dynamic elements, the link won't append to the
.btn-container


I know that there is
.on()
however I'm not sure how to use it after dynamic content is loaded, and I'm not exactly adding any events (yet) so I'm not sure what my other options.

So my question is, how can I append my new
<a>
element to
.btn-container
when
.btn-container
is already being dynamically added?

Here is project I'm working on: . http://45.55.34.137/p

Thanks.

Answer Source

What I assume it happens is that your admin.js runs before your ajax finishes. a thing you can do is this, in the admin.js pass initAdminControls to window just to make sure it is global like this.

window.initAdminControls = function () {
    var editBtn = $('<a class="waves-effect waves-light btn red darken-2"><i class="material-icons">grade</i>Edit</a>');
    $('.btn-container').append(editBtn);
}

and then in the done method call it like this

if (typeof window.initAdminControls === "function") { 
    window.initAdminControls();
}

this checks to see if that method exists and if yes it runs it

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download