Search code examples
jquerypaginationtumblr

Tumblr jQuery Pagination


I'm trying to paginate Tumblr's API v1 output on my website. I have the jQuery code and it works fine when displaying content, however, I need to allow it to become split and paginated for organizational purposes. The first box of code calls the API when

<div id="content"><div id=main"><div id ="tumblrFeed"></div><div class="clear"></div></div>

is called on the html page.

I'm having trouble being able to paginate my content when it's output on the browser. As you can see I have each page display 5 posts, and I've declared the variable tumblrPaginate to start at 0. I need the variable to change each time the user clicks on a "Previous or Next" button.

I've been working on this for quite some time, ballpark range is 2 weeks, without success. Any help or guidance is greatly appreciated. Please keep in mind that I'm a beginner with Javascript, jQuery, and the like.

    var tumblr_api_read = null; // this is important do not remove
    var tumblrPaginate = 0; // **TODO** make loop to increment each for pagination feature
    var tumblrpostCount = 5; // set the post count number, max is 50 for API v1

    $(document).ready(function() {  
            // setup our namespace
            $.tumblr = {};
            // modify these
            $.tumblr.url = 'http://wisdmlab.tumblr.com/api/read/json?callback=?&num=' + tumblrpostCount +'&start=' + tumblrPaginate +''; // set to display 7 posts. off set syntax is start=[postnumtobeginat]
            $.tumblr.numPostsToDisplay = 50;
            $.tumblr.postMaxDescriptionLength = 500; // set to -1 to turn off jquery.expander
            $.tumblr.videoWidth='200'; // youtube default 400
            $.tumblr.videoHeight='163'; // youtube default 325
            // do not modify these unless you are hardcore
            $.tumblr.imagePath = '..//testscripts/tumblr-jquery-master/img/';   
            $.tumblr.postCount = 0;

            reloadTumblr();
  });       

  function reloadTumblr(){      
    $("#tumblrFeed").empty();
    $("#tumblrFeed").append("<div class='body'>loading Tumblr</div>");

    $.ajax({
          url: $.tumblr.url,
          dataType: 'script',
          timeout: 10000,
      success:function(){ 
        $("#tumblrFeed").empty();
        if ((tumblr_api_read == undefined) || (tumblr_api_read == null)) {
            $("#tumblrFeed").append("<div class='title' href='#'>unable to load Tumblr</div>");
            $("#tumblrFeed").append("<div class='body'><a href=\"#\" onclick=\"javascript:reloadTumblr();\">[retry]</a></div>");                
            } else {
                //$("#tumblrFeed").append("<div class='body'><a href=\"#\" style=\"float:center\" onclick=\"javascript:reloadTumblr();\">Refresh News Page</a></div>");
                $.tumblr.postCount = 0;
            $.each(tumblr_api_read.posts.slice(0, 50), function(i,post){
                        if ($.tumblr.postCount >= $.tumblr.numPostsToDisplay) {
                            return;
                        }               
                    parseTumblrJSON(post);
                    $.tumblr.postCount++;
                });

                // Apply Expander
                if ($.tumblr.postMaxDescriptionLength > -1) {
                      $('div.expandable').expander({
                        slicePoint:       $.tumblr.postMaxDescriptionLength,  // default is 100
                        expandText:         'Read more.',
                        userCollapseText: 'Read less.'
                      });                                   
                }
            }
      },
      error:function (xhr, statusTxt, errorTxt){
            $("#tumblrFeed").append("<a class='title' href='#'>Tumblr Parse Error</a>");
            $("#tumblrFeed").append("<div class='body'>" + errorTxt + "<br/>" + xhr.responseText + "</div>");
      }                           
        });     
  }

    function formatDate(d) {
        return d.toString('dddd, MMMM d, yyyy')
    }

    function processResponse() {
    }

    function parseTumblrJSON(post) {
        //alert(post.type);
        var d = Date.parse(post["date-gmt"]);
        var dateFmt = formatDate(d);

    switch(post.type)
    {               
        case "regular":
        {
                $("#tumblrFeed").append(
                    "<table style='width: 100%;'><tr><td width='18px'>" +
                    "</td></table>");                       
            //Place directly before "</td>" <div class='date'>" + dateFmt + "</div>

            $("#tumblrFeed").append("<a class='title' href='" + post.url + "' target='_blank'>" + (post["regular-title"] == null ? 'view tumblr' : post["regular-title"])  + "</a>");
            $("#tumblrFeed").append("<div class='body expandable'>" + post["regular-body"] + "</div>");
            $("#tumblrFeed").append("<div class='date'>Posted on " + dateFmt + "</div>");
            break;
        }
        case "link":
        {
                $("#tumblrFeed").append(
                    "<table style='width: 100%;'><tr><td width='18px'>" +
                    "<a href='" + post.url + "' target='_blank'>" +
                    "<div class='date'>" + dateFmt + "</div></td></table>");                        

            $("#tumblrFeed").append("<a class='title' href='" + post["link-url"] + "' target='_blank'>" + (post["link-text"] == null ? 'view tumblr' : post["link-text"]) + "</a>");
            $("#tumblrFeed").append("<div class='body expandable'>" + post["link-description"] + "</div>");
            break;
        }               
        case "quote":
        {
                $("#tumblrFeed").append(
                    "<table style='width: 100%;'><tr><td width='18px'>" +
                    "<a href='" + post.url + "' target='_blank'>" +
                    "<div class='date'>" + dateFmt + "</div></td></table>");                        

            $("#tumblrFeed").append("<div class='body'>" + 
                "<div class='quote expandable'>" + post["quote-text"] + "</div>" +
                "<div class='quotesrc'>" + post["quote-source"] + "</div>" +
                "</div>");
            break;
        }               
        case "photo":
        {
                $("#tumblrFeed").append(
                    "<table style='width: 100%;'><tr><td width='18px'>" +
                    "<a href='" + post.url + "' target='_blank'>" +
                    "</td></table>");                       
            // valid values are: photo-url-[75, 100, 250, 400, 500, 1280]
            $("#tumblrFeed").append("<div class='body'>" + 
                "<a href='" + post.url + "'>" +
                "<img src='" + post["photo-url-250"] + "'/></a><br/>" + 
                post["photo-caption"] + 
                "</div>", "<div class='date'>Posted on " + dateFmt + "</div>");
            break;
        }
        case "conversation":
        {
                $("#tumblrFeed").append(
                    "<table style='width: 100%;'><tr><td width='18px'>" +
                    "<a href='" + post.url + "' target='_blank'>" +
                    "<div class='date'>" + dateFmt + "</div></td></table>");                        

            var html = '';
            $("#tumblrFeed").append("<a class='title' href='" + post.url + "' target='_blank'>" + (post["conversation-title"] == null ? 'view tumblr' : post["conversation-title"])  + "</a>");

                for(var i = 0; i < post["conversation"].length; i++) {
                    var conv = post["conversation"][i];                     
                    html += "<div class='convlabel'>" + conv.label + "</div>";
                    html += "<div class='convtext expandable'>" + conv.phrase + "</div>";
                }

                /*          
                $(this).find("line").each(function(){
                    html += "<div class='convlabel'>" + $(this).attr("label") + "</div>";
                    html += "<div class='convtext'>" + $(this).text() + "</div>";
                });*/

            $("#tumblrFeed").append("<div class='body'>" + html + "</div>");
            break;
        }
        case "audio":
        {
                $("#tumblrFeed").append(
                    "<table style='width: 100%;'><tr><td width='18px'>" +
                    "<a href='" + post.url + "' target='_blank'>" +
                    "<div class='date'>" + dateFmt + "</div></td></table>");                        

            $("#tumblrFeed").append("<a class='title' href='" + post.url + "' target='_blank'>" + post["audio-caption"] + "</a>");
            $("#tumblrFeed").append("<div class='body'>" + post["audio-player"] + "</div>");
            break;
        }
        case "video":
        {
                $("#tumblrFeed").append(
                    "<table style='width: 100%;'><tr><td width='18px'>" +
                    "<a href='" + post.url + "' target='_blank'>" +
                    "<div class='date'>" + dateFmt + "</div></td></table>");                        

            $("#tumblrFeed").append("<a class='title' href='" + post.url + "' target='_blank'>" + post["video-caption"] + "</a>");
            // resize our video code if possible
            var vdo = post["video-player"];
            var re = new RegExp('width=\"([a-zA-Z0-9]*)\"', 'g');
            vdo = vdo.replace(re, 'width="' + $.tumblr.videoWidth + '"');
            re = new RegExp('height=\"([a-zA-Z0-9]*)\"', 'g');
            vdo = vdo.replace(re, 'height="' + $.tumblr.videoHeight + '"');         
            re = new RegExp('400,320', 'g');
            vdo = vdo.replace(re, $.tumblr.videoWidth + ',' + $.tumblr.videoHeight);
            re = new RegExp('400,250', 'g');
            vdo = vdo.replace(re, $.tumblr.videoWidth + ',' + $.tumblr.videoHeight);
            $("#tumblrFeed").append("<div class='body'>" + vdo + "</div>");
            break;
        }               
        default:
            break;
    }
    $("#tumblrFeed").append("<div class='clear'>&nbsp;</div>");
    }

Solution

  • First I added the controls to the html doc

      <div id='controls'>
        <a href="#" id='next'>next</a>:<a href="#" id='previous'>previous</a>
      </div>
    

    Then preventDefault the links, increment tumblrPaginate, and reload the tumbler stream:

        $(document).ready(function() {
             (...)
             $.tumblr.imagePath = '..//testscripts/tumblr-jquery-master/img/';
             $.tumblr.postCount = 0;
    
             $('#next').on( "click", function (e) {
                 e.preventDefault();
                 tumblrPaginate += 5;
                 reloadTumblr();
             });
             $('#previous').on( "click", function (e) {
                 e.preventDefault();
                 if(tumblrPaginate>=5){
                      tumblrPaginate -= 5;
                      reloadTumblr();
                 }
             });
             reloadTumblr();
        });
    

    And finally in reloadTumblr() you will need to update the $.tumblr.url to include the new tumblrPaginate value:

      function reloadTumblr(){
         $("#tumblrFeed").empty();
         $("#tumblrFeed").append("<div class='body'>loading Tumblr</div>");
         $.tumblr.url = 'http://wisdmlab.tumblr.com/api/read/json?callback=?&num=' +
                        tumblrpostCount +'&start=' + tumblrPaginate + '';
         (....)
         }
    

    I couldnt get jsFiddle to work, so I uploaded it to my site: working example,js only.