Reputation: 15384
Im getting in a bit of a muddle with some jQuery im trying to put together. I am trying to loop through the first 5 tweets via a JSON dump within my app, with them then I would like to show one at a time in an animated loop..
My html
<div id="innerTwitter"> </div>
and the jQuery so far
var $container = $('#innerTwitter');
$.get('/feed', function(data) {
$container.empty();
$(data).slice(0,5).each(function(_, tweet) { // Grab first 5 Tweets
var $tweet = $(document.createElement('p'));
$tweet.text(tweet.text);
$container.append($tweet);
var ticker = function() {
setTimeout(function() {
$container.find('p:first').animate( {marginTop: '-90px'}, 500, function() {
$(this).detach().removeAttr('style');
});
ticker();
}, 10000);
};
ticker();
});
}, 'json');
So at the moment this is showing 5 tweets at the same time then removing 1 at a time until none are left, after which nothing else is displayed.
Could anyone give me some pointers please
Thanks
Upvotes: 0
Views: 146
Reputation: 3602
I think this is what you're after. This will display each of the tweets in turn with fading in and out.
var container = $("#innerTwitter");
function showTweets(tweets) {
var tweetPs = $.map(tweets, function (t) {
return $('<p></p>').text(t.text).hide();
});
container.append(tweetPs);
tweetPs[0].show();
var currentIndex = 0;
var nextTweet = function () {
var nextIndex = currentIndex == tweets.length - 1 ? 0 : currentIndex + 1;
tweetPs[currentIndex].fadeOut(400, function () {
tweetPs[nextIndex].fadeIn(400);
});
currentIndex = nextIndex;
};
setInterval(nextTweet, 2000);
}
showTweets([
{ text: "tweet1" },
{ text: "tweet2" },
{ text: "tweet3" },
{ text: "tweet4" },
{ text: "tweet5" },
]);
Here it is in action: http://jsfiddle.net/Tx8hj/1/
Upvotes: 1
Reputation: 1017
Try this
var container = $("#innerTwitter");
$.get('/feed', function(data) { showTweets($(data).slice(0,5)); }, 'json');
function showTweets(tweets) {
container.empty();
for (var i = 0; i < tweets.length; i++) {
var tweet = $("<p>").text(tweets[i].text);
tweet.hide();
tweet.appendTo(container);
}
tweets = container.children();
var showNext = function(index) {
if (index < tweets.length)
tweets.eq(index).fadeIn(400, function() { showNext(index + 1); });
}
showNext(0);
}
Example: http://jsfiddle.net/q8zXa/1/
Upvotes: 1