Within a jQuery AJAX call, I am using a $.each()
loop. Each element in the response data triggers the addition of a portion of HTML to a container class in my index.html file.
To view the code and ensure proper formatting, visit the codepen here as the pasted version may not display correctly due to mobile formatting issues.
$.each(responseData, function(i, item) {
/*
if(i > 4){
$($("section").last()).remove();
}
*/
try{
username = item.user.name;
user_text = item.text;
imgURL = item.user.profile_image_url;
hashtags = item.entities.hashtags;
let hashtagsDiv = ""
if(hashtags.length > 0){
hashtagsDiv = "<div class='row'><div class='col s10 offset-s2'>HASHTAGS: "
for(i = 0; i < hashtags.length; i++){
hashtagsDiv += "#"+hashtags[i].text+"; ";
}
hashtagsDiv += "</div></div>"
}
$("<div class ='row'>\
<div class ='col s12'>\
<section class='card-panel grey lighten-5 z-depth-1'>\
<div class='row valign-wrapper'>\
<div class='col s2'>\
<img src=\"" + imgURL + "\" alt='profile_pic' class='circle responsive-img'>\
</div>\
<div class='col s10'>\
<span class='black-text'> @" + username + " says: " + user_text + "</span>\
</div>\
</div>\
" + hashtagsDiv + "\
</section>\
</div>\
</div>").prependTo(".container").slideDown();
$(function(){
window.setTimeout(5000);
});
}
catch(err){
console.log("ERROR: " + err.message);
}
});
The prependTo()
method targets the .container
class within a <section>
tag in my HTML file. The elements are added as expected, with the latest one appearing at the top upon page reload. This behavior mimics a queue, stacking elements from the bottom up.
Presently, there are two issues that need attention:
The
setTimeout()
function does not produce the desired delay. All elements appear simultaneously, and I am struggling to implement a delay between each iteration. The intention is for each element to slide down every few seconds.Upon reaching a count of
i > 4
, I intend to remove the last element from the DOM in each cycle. This would maintain a maximum of 5 visible elements, with the oldest one removed at the end of each cycle to keep the queue updated. However, uncommenting the relevantif
block causes all elements to disappear from the screen.
I would greatly appreciate assistance in resolving these two issues. Thank you!