I am trying to add items into a div by appending to the end of the div during a for loop. The idea being I have records from a database with a "Total score" field, and I want the highest-scoring records on top.
The container div where I want to put the elements is this:
<div id="fetch-n-sites-output"></div>
And my callback function upon a successful AJAX call is as follows:
function updateNSites(data){
$("#fetch-n-sites-output").empty();
data["fetched-sites"].map(function(element, index){
var cloned = cloneTemplate(index, element);
console.log(`Processing site ${index}...`);
$("#fetch-n-sites-output").append(cloned);
});
}
For completeness, my cloneTemplate function is this:
function cloneTemplate(index, data){
// CLONE TEMPLATE
var template = $("#test-template").html().trim();
var clone = $(template);
var siteID = data["site_id"];
var totalSiteScore = data["total_site_score"];
// UPDATE CLONE WITH SITE-SPECIFIC INFORMATION
// 0. Update ID of div element with site id
var mainDiv = $("div.greendiv").eq(index);
mainDiv.attr("id", `site-${siteID}`);
// 1. Update header with "Site ID: {site_id}"
$(`#site-${siteID} > div.reddiv > p.header-text`).text(`Site ID: ${siteID} - Total Score: ${totalSiteScore}`);
// 2. Add event handlers
// $(`#site-${siteID} div.site-sidenav`).on("click", 'a', function() {
// alert("clicky");
// });
$(`#site-${siteID}`).find(".site-navlink").on("click", function () {
alert("clicky");
});
// SHOW CLONE
clone.removeClass("template-hidden").addClass("template-show");
return clone;
}
When I retrieve 3 sites, the highest scoring site is always at the bottom. This doesn't make sense to me, because my SQL query orders by this total site score. The highest scoring site is always placed at the bottom, but the other sites are ordered properly:
Another odd problem (which I think is related to this main issue) is that the event handlers that I add in the cloneTemplate function to handle clicks on the <a> tags (right now just calls an alert() for testing) only work on the elements other than the first:
Whereas clicking 'GENERAL' on the first element does not trigger an alert. Could someone please help me figure out why every added element but the first behaves properly, but the first does not? And why the first element is always getting placed at the bottom? Thank you