ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Paginating retrieved Tumblr posts

Updated on May 29, 2014
Credit: Tumblr
Credit: Tumblr

As I wrote in my previous hub that I will explain how we can paginate the Tumblr posts we retrieve, so here is what I have been working on.

Paginating Retrieved Tumblr Posts

As you know all the codes I have written are in jQuery so obviously this one is jQuery too. The reason that I use jQuery is that it is pretty easy and understandable. First of all I will show you the whole code and then explain every bit of it.

<!DOCTYPE html>
<html lang="en">
<head>
	<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
	<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
	<title>Fetching Tumblr blog posts</title>
</head>
<body>
<h1 style="text-align: center;">Fetching Tumblr blog posts</h1>
<div id="results" style="margin-left:auto; margin-right: auto; width: 300px;">

</div>
<div id="page" style="margin-left:auto; margin-right: auto; width: 800px; text-align: center;"></div>
<script>
$(document).ready(function() {
var o = 0;
	if (window.location.search.indexOf('page=') > -1) {
		var url = $(location).attr('href');
		url = url.split("=");
		o = url[1] * 10 - 10;
	}

$.ajax({ 
    type: 'GET', 
    url: 'http://api.tumblr.com/v2/blog/rofl-gifs.tumblr.com/posts?api_key=4k2NGQU1cJZ4d1ZqrvKR9mnpUUmubGPlyUEzDZfiL5loPeIOzv&offset=' + o + '&limit=10', 
    data: { get_param: 'value' }, 
    dataType: 'jsonp',
    success: function (data) { 
				for (i = 0; i < data.response.posts.length; i++) {
					$('#results').append('<div style="text-align: center; border-top: 1px solid #aaa; width: 300px;"><a href="' + data.response.posts[i].post_url +'"> ' + data.response.posts[i].caption + '<img align="center" src="' + data.response.posts[i].photos[0].alt_sizes[0].url + '"></a></div><br/><br/>');
				}
					var result = 0;
					result = data.response.total_posts / 10;
					
					for (j = 1; j <= result.toFixed(0); j++) {
						$('#page').append('<a style="border: 1px solid #ccc; margin: 2px; border-radius: 5px; text-decoration: none; padding: 5px 10px; color: #000;" href="?page=' + j + '">' + j + '</a>');
					}
				
    }
});

});
</script>
</body>
</html>

Explanation

You probably know what the <!DOCTYPE html> , <html> , <head> and <body> attributes are therefore I'm gonna explain the main parts.

	<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
	<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>

The above code loads the jQuery framework and then the page Title is defined which is "Fetching Tumblr blog posts". Right when the page body starts there is a heading which is the same as the page title "Fetching Tumblr blog posts". After the heading there is a div container which has the "results" id, this is where the retrieved posts are gonna be inserted and and shown on the page. After the results container is another div container which has the "page" id, this is where links to every single page will be placed.

Now let's get to the jQuery Code.

jQuery Code

jQuery logo. Credit: jQuery.com
jQuery logo. Credit: jQuery.com
$(document).ready(function() {
var o = 0;
	if (window.location.search.indexOf('page=') > -1) {
		var url = $(location).attr('href');
		url = url.split("=");
		o = url[1] * 10 - 10;
	}

$.ajax({ 
    type: 'GET', 
    url: 'http://api.tumblr.com/v2/blog/rofl-gifs.tumblr.com/posts?api_key=4k2NGQU1cJZ4d1ZqrvKR9mnpUUmubGPlyUEzDZfiL5loPeIOzv&offset=' + o + '&limit=10', 
    data: { get_param: 'value' }, 
    dataType: 'jsonp',
    success: function (data) { 
				for (i = 0; i < data.response.posts.length; i++) {
					$('#results').append('<div style="text-align: center; border-top: 1px solid #aaa; width: 300px;"><a href="' + data.response.posts[i].post_url +'"> ' + data.response.posts[i].caption + '<img align="center" src="' + data.response.posts[i].photos[0].alt_sizes[0].url + '"></a></div><br/><br/>');
				}
					var result = 0;
					result = data.response.total_posts / 10;
					
					for (j = 1; j <= result.toFixed(0); j++) {
						$('#page').append('<a style="border: 1px solid #ccc; margin: 2px; border-radius: 5px; text-decoration: none; padding: 5px 10px; color: #000;" href="?page=' + j + '">' + j + '</a>');
					}
				
    }
});

});

Normally the Tumblr API returns 20 posts but we wil limit the post count to 10, you remove the limit parameter and use all of the twenty posts.

First of all we should declare a variable which will contain the value of offset. As you can see in the above code after the $(document).ready() function, variable o is declared and its value is 0.

var o = 0;

And then we should run an if statement to check if there is any parameter in the url because we will use different parameters for pagination not different pages.

if (window.location.search.indexOf('page=') > -1)

The above code checks if the current url contains an attribute of "page=". If it does then

		var url = $(location).attr('href');
		url = url.split("=");
		o = url[1] * 10 - 10;

The above code is run which splits the url into an array the first value of this array will contain the part of url which comes before "=" and the second is which comes after "=". Because arrays are 0 indexed we will use the url[1] which is the second value. Now url[1] will be multiplied by 10 and then subtracted by 10, does it make any sense? Yes, it does! If the user is on page one we don't want to start from post number 10 therefore 1 will be multiplied by 10 and then subtracted by 10 giving us the value of 0 so we can start from the last post (first post according to Tumblr API). If the user is on page 2 then the value will be 10 and posts from 10 to 20 will be retrieved.

If the url does not contain any parameter then the if statement will be false and the code inside its braces will not execute thus leaving the value of variable o to 0.

After this the $.ajax function is run to retrieve the posts.

$.ajax({ 
    type: 'GET', 
    url: 'http://api.tumblr.com/v2/blog/rofl-gifs.tumblr.com/posts?api_key=4k2NGQU1cJZ4d1ZqrvKR9mnpUUmubGPlyUEzDZfiL5loPeIOzv&offset=' + o + '&limit=10', 
    data: { get_param: 'value' }, 
    dataType: 'jsonp',
    success: function (data) { 
				for (i = 0; i < data.response.posts.length; i++) {
					$('#results').append('<div style="text-align: center; border-top: 1px solid #aaa; width: 300px;"><a href="' + data.response.posts[i].post_url +'"> ' + data.response.posts[i].caption + '<img align="center" src="' + data.response.posts[i].photos[0].alt_sizes[0].url + '"></a></div><br/><br/>');
				}
					var result = 0;
					result = data.response.total_posts / 10;
					
					for (j = 1; j <= result.toFixed(0); j++) {
						$('#page').append('<a style="border: 1px solid #ccc; margin: 2px; border-radius: 5px; text-decoration: none; padding: 5px 10px; color: #000;" href="?page=' + j + '">' + j + '</a>');
					}
				
    }
});

For a complete understanding of the above code, please click here to read one of my previous hubs.

As you can see in the above code the URL from where the posts are retrieved contains 3 parameters api_key, offset and limit. API key is necessary for using the Tumblr API, offset is the starting point of post if we want to define one and we can use limit to limit the number of posts returned.

url: 'http://api.tumblr.com/v2/blog/rofl-gifs.tumblr.com/posts?api_key=4k2NGQU1cJZ4d1ZqrvKR9mnpUUmubGPlyUEzDZfiL5loPeIOzv&offset=' + o + '&limit=10', 

The value of offset is the value of variable o, to paginate the posts we have to use the value of o as the offset. Upon success a for loop is run

for (i = 0; i < data.response.posts.length; i++) {
					$('#results').append('<div style="text-align: center; border-top: 1px solid #aaa; width: 300px;"><a href="' + data.response.posts[i].post_url +'"> ' + data.response.posts[i].caption + '<img align="center" src="' + data.response.posts[i].photos[0].alt_sizes[0].url + '"></a></div><br/><br/>');
				}

The above code loops through the post array and appends the Post URL, Post Caption and Image source in the results container.

Right after the for loop you can see another code which calculates the total amount of posts and creates the number of pages.

var result = 0;
result = data.response.total_posts / 10;

First the result variable is declared with a value of 0 and then the total number of posts is divided by 10 and the result is passed to the variable "result". Total number of posts is divided by 10 because we are showing 10 posts on each page, you should divide it by the number of posts you want to show on each page.

for (j = 1; j <= result.toFixed(0); j++) {
						$('#page').append('<a style="border: 1px solid #ccc; margin: 2px; border-radius: 5px; text-decoration: none; padding: 5px 10px; color: #000;" href="?page=' + j + '">' + j + '</a>');
					}

Right after the calculation of page is done another for loop is run, the code is mentioned above. Because the result of the page's calculation is a floating point number we have to use this function

result.toFixed(0)

The above code turns the result into a round number and a variable is declared the loop puts every number in the page container with a link like index.html?page=1.

Every time the link is clicked the page reloads with the page parameter and page number the user clicked and the posts are retrieved according to the page number.

Please click here for a demo.

Comments

    0 of 8192 characters used
    Post Comment

    • smga22 profile image

      smga22 3 years ago from Dhaka, Bangladesh

      Nice Hub.

    • Ali Darakhshaan profile image
      Author

      Ali Ahmed 3 years ago from Karachi, Pakistan

      Thanks

    Click to Rate This Article