이번 내용은 먼저 트위글 15개 리스트를 보여주고, 제일 하단의 글을 보고 스크롤을 선택하면, 16-30 개 사이의 리스트를
보여주는 기술이다.
// Set the size for each page to load
var pageSize = 15;
// Username to load the timeline from
var username = 'marcofolio';
// Variable for the current page
var currentPage = 1;
Now, we need to call a function that'll load the first page.
// First time, directly load the tweets
loadTweets();
The loadTweets()
code is wrapped inside a function, since we'll need to call it over and over to load more tweets. This is how it looks like:
// Loads the next tweets
var loadTweets = function() {
var url = "http://twitter.com/status/user_timeline/"
+ username + ".json?count="+pageSize+"&page="+currentPage+"&callback=?";
$.getJSON(url,function(data) {
$.each(data, function(i, post) {
appendTweet(post.text, post.id);
});
// We're done loading the tweets, so hide the overlay
$("#overlay").fadeOut();
});
};
// Appends the new tweet to the UI
var appendTweet = function(tweet, id) {
$("<p />")
.html(tweet)
.append($("<a />")
.attr("href", "http://twitter.com/" + username + "/status/" + id)
.attr("title", "Go to Twitter status")
.append($("<img />")
.attr("src", "images/link.png")
)
)
.appendTo($("#tweets"));
};
We're using the jQuery function to dynamically the tweet paragraphs. We also add the link to the tweet by showing an image. We append the new element to the #tweets
container and we're done!
But now, we have the initial fill (the first page). We now need to detect that the user is scrolling the #tweets
container and find out if he is at the bottom to load the next page. Here's how this can be achieved:
// Append a scroll event handler to the container
$("#tweets").scroll(function() {
// We check if we're at the bottom of the scrollcontainer
if ($(this)[0].scrollHeight - $(this).scrollTop() == $(this).outerHeight()) {
// If we're at the bottom, show the overlay and retrieve the next page
currentPage++;
$("#overlay").fadeIn();
loadTweets();
}
});