rnmp/salvattore

EXAMPLE - how to insert lots of new elements (e.g. from AJAX) - using jQuery

claudeschneider opened this issue · 1 comments

I spent quite a while trying to add lots of new items to the grid from AJAX, so wanted to share in case it's helpful.
The example given by Salvattore is a bit of a hack. For each item they want to add, they create an empty "article" DOM element, call appendElements with it, and then replace that item with the outerHTML they really want to add. And repeat for all elements.

Instead, you can convert lots of jQuery elements into an array, and insert them in one go:

var masonry_container = document.getElementById('masonry_container');
var new_items = []; // array to contain our DOM elements
// for each element we want to add, selected using jQuery, append it to our array
$('.my_jQuery_selector').each(function()
{
    new_items.push($(this)[0]); // use [0] to get at the DOM element
});
salvattore.appendElements(masonry_container, new_items);

This should be added to the documentation, as it seems like a common use case (pagination).

Thanks for the snippet!

However I'm really struggling to make the append work inside the Ajax call... data to DOM objects, how?

$.ajax({ type: "GET", url: "<?=get_site_url()?>/wp-admin/admin-ajax.php", dataType: 'html', data: ({ action: 'loadMore', number: number, posts: posts, cpt: cpt }), beforeSend : function(xhr, opts){ $("#box-load-more a i").show(); }, success: function(data){ $container.append(data); // How can I get data to become DOM objects? posts = posts + number; }, complete : function() { $("#ajax-reload-button i").hide(); } });