josephsnell josephsnell - 1 month ago 4
HTML Question

How to show/hide an unordered list that is generated

I am using this code to generate the last 5 tweets from a given user.

What I am trying to do is to show each tweet one at a time.

I've modified the script so that the generated has an id. You can see the change I made on line 6 of the script.

Here is the script i'm using:

$(document).ready(function () {
var tweets = $('#tweetlist li').hide();
i = 0;

(function cycle() {

tweets.eq(i).fadeIn(600)
.delay(4000)
.fadeOut(600, cycle);

i = ++i % tweets.length;

})();
});


For some reason it just doesn't work. I have jquery called before both scripts, but the list still shows all of the items.

Here is the jsfiddle i've been using:
http://jsfiddle.net/wulfmann/qst8atkk/1/

The weird thing is that if I build the list myself it works.

I have a feeling that i'm missing something fundamental. Admittedly I have not gone through the twitter script code line by line, so I may have missed something there.

I am learning jquery and javascript now so I'd just like to make sure i'm not missing something basic.

edit: In the attached jsfiddle i've unminified the js so that you can see.

Answer

Your fadeIn / fadeOut loop is fine. However, in your example you run it after documents load, and before the async action (fetching the tweets) ends, which means the tweets list is empty, and afterwards the full list is rendered.

To prevent that use the customCallback options in the config. After the items are fetched, the callback will render them, hide them, and then execute the fadeIn / fadeOut loop (demo):

var configProfile = {
  "profile": {"screenName": 'twitter'},
  "maxTweets": 5,
  "enableLinks": true, 
  "showUser": true,
  "showTime": true,
  "showImages": false,
  "customCallback": handleTweets,
  "lang": 'en'
};
twitterFetcher.fetch(configProfile);

function handleTweets(tweets) {
    var x = tweets.length;
    var n = 0;
    var element = document.getElementById('tweets');
    var html = '<ul>';
    while(n < x) {
      html += '<li>' + tweets[n] + '</li>';
      n++;
    }
    html += '</ul>';
    element.innerHTML = html;

    var tweets = $(element).find('li').hide();

    var i = 0;

    (function cycle() { 

      tweets.eq(i).fadeIn(600)
        .delay(4000)
        .fadeOut(600, cycle);

      i = ++i % tweets.length;

    })();
}