I’m having a little problem with the .length() property. I’m trying to count the number of spans in each div with a same class. Those Divs are appended previously in the script. The funny thing is, if I alert the variable corresponding to the length, everything works fine, if I remove the alert, it doesn’t. Never seen that before so any help would be appreciated 🙂 Here is the code :
getTweets();
tweetCounter = function(){
$('.entry').each(function(){
var nTweets = $('.tweet', this).length;
var infoPane = $('.infoPane', this);
var tLink = '<a href="#" class="tLink" title="Tweets of the day">' + nTweets + ' Tweets that day</a>';
infoPane.append(tLink);
//alert(nTweets);
});
}
tweetCounter();
As I said, it appends correctly when I uncomment the alert. If commented, 0 is displayed on every DIV…
Any ideas ?
Here’s the getTweets function :
getTweets = function(){
var url = "http://twitter.com/status/user_timeline/charleshaa.json?count=30&callback=?";
$.getJSON(url, function(data){
$.each(data, function(i, item) {
var fullTDate = item.created_at;
var splitTDate = fullTDate.split(" ");
var tMonth = splitTDate[1];
if (tMonth == "Jan"){
tMonth = "01"
} else if(tMonth == "Feb"){
tMonth = "02"
} else if(tMonth == "Mar"){
tMonth = "03"
} else if(tMonth == "Apr"){
tMonth = "04"
} else if(tMonth == "May"){
tMonth = "05"
} else if(tMonth == "Jun"){
tMonth = "06"
} else if(tMonth == "Jul"){
tMonth = "07"
} else if(tMonth == "Aug"){
tMonth = "08"
} else if(tMonth == "Sep"){
tMonth = "09"
} else if(tMonth == "Oct"){
tMonth = "10"
} else if(tMonth == "Nov"){
tMonth = "11"
} else if(tMonth == "Dec"){
tMonth = "12"
}
var tDay = splitTDate[2];
var tYear = splitTDate[5];
var tDate = tDay + '-' + tMonth + '-' + tYear;
var tText = '<span class="tweet">' + item.text + '</span>';
//alert(tDate);
var destination = $('#date_'+ tDate +'');
destination.append(tText);
});
});
}
Based on your comment. It pretty much looks like that the function which adds the
.tweetelements does this asyncronously (maybe an ajax-request ?) If that is the case, the method does not block the code execution and again, this would bring your behavior.What you would need to do in this case is, provide a callback function to the function which gets and creates the tweets. If that has finished, execute the callback.
This is how it could look like in jQuery 1.5.2+. The
get_tweets()function here fires 5 requests and stores theDeferredobject in an array which is returned.$.when()will fire when all promises are fulfilled.update
Here is how it should look like with 1.3.2:
and then call it like