magicPenguin
magicPenguin

Reputation: 35

Refreshing JSON

I'm using the following code to retrieve a simple list of tweets containing a certain hash tag:

$(document).ready(function tweetList() {
$.getJSON(
    'http://search.twitter.com/search.json?callback=?&rpp=20&q=web',
    function(data) {
        $.each(data, function(i, tweets) {
            for (var num = 0, len = tweets.length; num < len; num++) {
                if (tweets[num].text !== undefined) {
                    var tim = new Date(tweets[num].created_at);
                    var author = tweets[num].from_user;
                    $('ul#tweets').append('<li><b>' + tim.toString().substring(0, 24) + ':</b> ' + tweets[num].text + author + '</li>');   
                }
            }
        });
        setInterval(tweetList, 5000);
    }
);
});</script>

<ul id="tweets"></ul>

As you can see I am trying to refresh the list, however the problem is that by refreshing the function, the list keeps growing with the refreshed data.

I know this is because I am using .append, however when I use .html the whole list of tweets doesn't get populated.

Is it possible to get around this? Thanks.

Upvotes: 0

Views: 198

Answers (3)

epascarello
epascarello

Reputation: 207537

Use jQuery's empty()

$('#tweets').empty();
$.each(data, function(i, tweets) {

Upvotes: 1

MaddHacker
MaddHacker

Reputation: 1128

I'm guessing you want to remove old tweets, but not all of them. The:

$('ul#tweets').html('')

Will remove all old tweets before you update, but this will let you keep an arbitrary number of tweets (set by numToKeep);

var numToKeep=10;
var currSize = $('ul#tweets li').size();
var extras = numToKeep - currSize;
$('ul#tweets li').each(function(count,el){
   if (count < numToKeep) {
      $(el).remove();
   }
});

Since count is 0 based, this should remove old tweets.

Upvotes: 1

antyrat
antyrat

Reputation: 27765

You need to delete your previous data before inserting new.

Before $.each write:

$('ul#tweets').html('');

Upvotes: 1

Related Questions