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.


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 = {
const source = $('#item-template').html();
const template = Handlebars.compile(source);
const html = template(context);


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>');


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

I know that there is
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
element to
is already being dynamically added?

Here is project I'm working on: .


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>');

and then in the done method call it like this

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

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