Reputation: 73
I get data from an external JSON file that I loop through with jQuery each and then output to HTML.
Since the JSON data updates quite often I also want to update the HTML in these divs every minute or so. I've been reading up on this and understand that the easiest way to accomplish this is to use html() instead of append(). This does not work for me since it only outputs the last div in my loop.
With append it outputs all of my divs but, of course, they keep stacking when the script runs again. I've tried working around this by clearing the div I'm appending to before I do anything else, but this results in a horrible flickering.
Is there any way to solve this?
Here is the code with my empty() workaround.
<div class="content lounge-content"></div>
<script type="text/javascript">
function repeat(){
$('.lounge-content').empty();
$.getJSON('https://api.import.io/store/data/dde648b1-fae1-49c1-a4b8-a084e34119fd/_query?input/webpage/url=http%3A%2F%2Fcsgolounge.com%2F&_user=213e76f7-c31e-4e56-bd2f-b7463aa8df8e&_apikey=213e76f7c31e4e56bd2fb7463aa8df8e4d47f273f4f49901a03092c93455f74df3cb1f165c675c467e69380c0f2fcac66cbbe5db7e92a0764d915fc8ab62f46a64e1298b3514ce2c2d6fd43f211f91a7', function(data)
{
$.each(data.results, function(key, val) {
$(".lounge-content").append('<a href="'+val.MATCH_LINK+'" target="_blank"><div class="lounge-item"><p>'+val.whenm_text+'</p><h3>'+val.team1+'</h3><span>'+val.team1_percent+'</span><p> - </p><span>'+val.team2_percent+' </span><h3>'+val.team2+'</h3><p>'+val.best_of+', '+val.EVENTM_TEXT+'</p></div></a><hr>');
})
});
}
setInterval(repeat, 5000);
</script>
Upvotes: 1
Views: 2007
Reputation: 46323
Construct one "long" string of your entire HTML and set that as the html property:
function repeat() {
$.getJSON('https://api.import.io/store/...', function(data) {
var longHTML = '';
$.each(data.results, function(key, val) {
longHTML += '<a href="'+val.MATCH_LINK+'" target="_blank"><div class="lounge-item"><p>'+val.whenm_text+'...';
});
$(".lounge-content").html(longHTML);
});
}
setInterval(repeat, 5000);
As an added "bonus", you'd get improved performance since manipulating strings is much faster than manipulating DOM.
Upvotes: 1
Reputation: 3169
You should empty the html parts after fetching the json data
function repeat(){
$.getJSON('url', function(data) {
$('.lounge-content').empty();
$.each(data.results, function(key, val) {
$(".lounge-content").append('thing');
})
});
}
Upvotes: 1