I want to show a subsection of some projects on my webpage. I have an array of project names and some corresponding data in html files, like in the example below. I have a button with some preview-content in it, and if a user clicks on that it opens up the full container with all the project details.
To do this I though to loop through a sliced array in reverse and prepend the code to a div element on my webpage. The content often loads fine, but sometimes when I refresh the page it will display the previews in a different order than as defined in the array. Also, sometimes "previewtitle" and "previewcontent" return undefined, but not all the time. What am I doing wrong here?
I want to prepend the projects dynamically in the same order on every refresh.
var $projectNames = [ "coolprojecthere", "andanotherone", "moreprojects", "lastone" ];
projects/coolprojecthere.html looks like this:
<div id="title">Project title here</div>
<div id="content">Content html here</div>
projects/previews/coolprojecthere.html looks like this:
<div id="title">Project title here</div>
<div id="content">Content text here</div>
I loop through them like this to prepend them:
$projectNames = $projectNames.slice(0, 7);
$.each($projectNames.reverse(), function (index, projectname) {
var previewtitle, previewcontent;
$.get("projects/previews/" + projectname + ".html", function (prevdata) {
previewtitle = $(prevdata).filter('#title').text();
previewcontent = $(prevdata).filter('#content').text();
});
$.get("projects/" + projectname + ".html", function (data) {
var project = "<section id=\"project\" class=\"\"> \
<t>" + previewtitle + "</t><br /> \
<p>" + previewcontent + "</p> \
</div> \
<div class=\"content\"> \
<h5>" + $(data).filter('#title').text() + "</h5> \
<div class=\"content-container\">"
+ $(data).filter('#content').html() +
"</div> \
</div> \
</section>"
$('#main-container').prepend(project);
});