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

    • Ali Darakhshaan profile imageAUTHOR

      Ali Ahmed 

      4 years ago from Karachi, Pakistan

      Thanks

    • smga22 profile image

      smga22 

      4 years ago from Dhaka, Bangladesh

      Nice Hub.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)