jQuery Project to Search Tumblr API User Blog Posts & Images & Display it on Website With Pagination in Javascript Full Project For Beginners

 

 

 

index.html

 

 

<!DOCTYPE html>
<html>
<head>
    <title>Tumblr Posts</title>
    <meta name="viewport" content="width=device-width">
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta charset="utf-8">
    <style>
        @import url(http://fonts.googleapis.com/css?family=Noto+Sans:400,700,400italic,700italic);
 html, body {
	 background-color: #000;
	 color: #fff;
	 font-size: 0.9em;
}
 html, body, input {
	 font-family: 'Noto Sans', Arial, sans-serif;
}
 input {
	 border: 0;
	 padding: 0 2px;
}
 html, body, h1, h2, h3, h4, h5, h6, form, .post .caption p {
	 margin: 0;
	 padding: 0;
}
 #images, #form {
	 width: 100%;
	/* max-width: 700px;
	 */
	 margin-left: auto;
	 margin-right: auto;
}
 @media screen and (max-width: 1280px) {
	 #images, #form {
		 max-width: 100% !important;
	}
}
 #navigation {
	 text-align: center;
	 margin: 30px 0px;
}
 a.navbutt {
	 padding: 6px 10px;
	 margin: 10px;
	 background-color: #666;
	 border-radius: 5px;
	 text-decoration: none;
}
 @media screen and (max-width: 480px) {
	 a.navbutt {
		 padding: 3px 5px;
		 margin: 3px;
	}
}
 a.navbutt:link, a.navbutt:visited {
	 color: #fff;
}
 a.navbutt:hover {
	 background-color: #777;
}
 a.navbutt:active {
	 padding: 5px 9px;
}
 a.disabled {
	 background-color: #333 !important;
}
 a.disabled:link, a.disabled:visited {
	 color: #999;
}
 a.disabled:hover {
	 background-color: #333 !important;
}
 a.disabled:active {
	 padding: 6px 10px !important;
}
 .post {
	 margin-bottom: 20px;
	 color: #fff;
}
 .post h2 {
	 padding: 0;
}
 .post p {
	 margin: 10px 0;
}
 .post figure {
	 margin: 0;
}
 .video {
	 position: relative;
	 padding-top: 25px;
	 padding-bottom: 56.25%;
	/* 16:9 = 9/16*100 */
	 height: 0;
}
 .video iframe.instagram-media {
	 max-width: 100% !important;
}
 .video iframe, .video embed, .video object {
	 position: absolute;
	 top: 0;
	 left: 0;
	 width: 100%;
	 height: 100%;
	/*&:not(.instagram-media) {
		 height: 100%;
	}
	*/
}
 .html5-video video {
	 width: 100% !important;
	 height: auto !important;
}
 .images a img {
	 display: block;
	 width: 100%;
	 margin: 0;
	 margin-top: 20px;
}
 .images a:first-child img {
	 margin-top: 0;
}
 .audio, .audio iframe {
	 width: 100%;
	 height: 116px;
}
 .caption {
	 background-color: #222;
	 color: #999;
	 padding: 10px 20px;
	 font-size: 11px;
	 overflow-x: hidden;
}
 .source {
	 color: #999;
	 font-size: 9px;
	 padding: 3px 0px;
	 overflow-x: hidden;
}
 .grey {
	 color: #666;
}
 a:link, a:visited, a:active {
	 color: #666;
}
 a:link.nolink, a:visited.nolink, a:active.nolink {
	 color: #fff;
	 text-decoration: none;
}
 #showform, #advoptions, #navigation {
	 display: none;
}
 #form, #inputform {
	 text-align: center;
	 margin-top: 5px;
}
 #form .main, #inputform .main {
	 font-size: 150%;
}
 #advoptions {
	 margin-top: 10px;
}
 label {
	 font-weight: bold;
}
 .plain {
	 font-weight: normal;
}
 blockquote {
	 margin: 5px 20px;
}
 
    </style>
    <style type="text/css" id="imgwidth"></style>
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/jquery.ba-bbq/1.2.1/jquery.ba-bbq.min.js"></script>
    <script>
        (function($) {
    $.TumblrPosts = function(element, options) {
        var defaults = {
            tumblrId: null,
            postId: null,
            start: 0,
            num: 50,
            tagged: null,
            ptype: null
        };

        var self = this;
        self.settings = {};
        self.tumblr = {};
        var $element = $(element);
        
        self.init = function() {
            self.settings = $.extend({}, defaults, options);
            if (self.settings.tumblrId) self.load();
        };
        
        /// Public methods
        self.load = function (newOptions) {
            self.settings = $.extend(self.settings, newOptions);
            $.ajax({
                type: 'GET',
                cache: true,
                url: 'http://' + self.settings.tumblrId + '.tumblr.com/api/read/json/?' + 
                    (self.settings.postId ? 'id=' + self.settings.postId : 
                        'start=' + self.settings.start + '&num=' + self.settings.num + 
                        (self.settings.tagged ? '&tagged=' + self.settings.tagged : '') + 
                        (self.settings.ptype ? '&type=' + self.settings.ptype : '')
                    ), 
                dataType: 'jsonp',
                jsonpCallback: 'jqTumblrHandlr',
                success: onLoad
            });
            clear();
        };
        
        /// Private methods
        var onLoad = function (tumblr) {
            self.tumblr = tumblr;
            console.log(tumblr);
            
            // Title
            $element.append('<h1>' + tumblr.tumblelog.title + '</h1>');
            window.document.title = tumblr.tumblelog.title + ' - Tumblr';
                
            for (var i in tumblr.posts) {
                if (tumblr.posts[i].type == 'photo') {
                    imgPost(tumblr.posts[i]);
                } else if (tumblr.posts[i].type == 'regular') {
                    regPost(tumblr.posts[i]);
                } else if (tumblr.posts[i].type == 'video') {
                    videoPost(tumblr.posts[i]);
                } else if (tumblr.posts[i].type == 'audio') {
                    audioPost(tumblr.posts[i]);
                } else {
                    console.log(tumblr.posts[i]);
                }
            }
            forceVideoControls();
        };
        var clear = function () {
            $element.empty();
        };
        var forceVideoControls = function () {
            $element.find('video').each(function() {
                $(this).prop("controls", true);
            });
        };
        var cleanHTML = function (htmlText) {
            //return $('<span>' + htmlText + '</span>').text();
            var allTagsExcept = /<(?!\/?(a|p|br|blockquote)(?=>|\s.*>))\/?.*?>/ig;
            var result = htmlText.replace(allTagsExcept, '');
            //console.log({before: htmlText, after: result});
            return result;
        };
        var imgPost = function (post) {
            var $post = $('<div class="post"></div>');
            var photos = (post.photos && post.photos.length > 0) ? post.photos : [post];
            var photosHTML = ['<div class="images">'];
            var imgsrc;
            for (var i in photos) {
                imgsrc = photos[i]['photo-url-500'].match(/\.gif$/ig) ? photos[i]['photo-url-500'] : photos[i]['photo-url-1280'];
                photosHTML.push('<a class="nolink hoverZoomLink" href="' + imgsrc + '" target="_blank">',
                '<img src="' + imgsrc + '">',
                '</a>');
            }
            photosHTML.push('</div>');
            $post.append(photosHTML.join(''));
            
            if (post['photo-caption']) {
                $post.append('<div class="caption">' + cleanHTML(post['photo-caption']) + '</div>');
            }
            addSource($post, post);
            $element.append($post);
        };
        var videoPost = function (post) {
            if (post['video-player-500']) {
                var $post = $('<div class="post"></div>');
                var vidClass = post['video-player-500'].match(/<video/ig) ? 'html5-video' : 'video';
                $post.append('<div class="' + vidClass + '">' + post['video-player-500'] + '</div>');
                
                if (post['video-caption']) {
                    $post.append('<div class="caption">' + cleanHTML(post['video-caption']) + '</div>');
                }
                addSource($post, post);
                $element.append($post);
            }
        };
        var audioPost = function (post) {
            var $post = $('<div class="post"></div>');
            $post.append('<div class="audio">' + post['audio-player'] + '</div>');
            
            if (post['audio-caption']) {
                $post.append('<div class="caption">' + cleanHTML(post['audio-caption']) + '</div>');
            }
            addSource($post, post);
            $element.append($post);
        };
        var regPost = function (post) {
            var $post = $('<div class="post"></div>');
            if (post['regular-title']) {
                $post.append('<h2>' + post['regular-title'] + '</h2>');
            }
            if (post['regular-body']) {
                $post.append('<div class="images"><a class="nolink" href="' + post['url-with-slug'] + '" target="_blank">' + post['regular-body'] + '</a></div>');
            }
            addSource($post, post);
            $element.append($post);
        };
        var addSource = function ($post, post) {
            $post.append(
                '<div class="source">Source: <a href="' + post['url-with-slug'] + '" target="_blank">' + post['url-with-slug'] + '</a>' + 
                (post.hasOwnProperty('photo-link-url') ? ' Link: <a href="' + post['photo-link-url'] + '" target="_blank">' + post['photo-link-url'] + '</a>' : '') + 
                '</div>'
            );
        };

        self.init();
    };

    $.fn.TumblrPosts = function(options) {
        return this.each(function() {
            if (undefined === $(this).data('TumblrPosts')) {
                var plugin = new $.TumblrPosts(this, options);
                $(this).data('TumblrPosts', plugin);
            }
        });
    };

})(jQuery);

/* Setup page stuff */
$(function() {
    //window.tumblrPosts = $('#images').TumblrPosts({tumblrId: 'fer1972'}).data('TumblrPosts');
    
    window.tumblrPosts = $('#images').TumblrPosts().data('TumblrPosts');
    $(window).resize(function () {
        var w = $(window).height() * 2 / 3; // Most images are 3/2, fit to screen height
        $('#imgwidth').text("#images,#form {max-width: " + w + "px;}");
    });
    $(window).trigger('resize');
    var prevId;
    $('#form').submit(function(e) {
        e.preventDefault();
        if ($('#tumblrId').val() !== prevId) $('#start').val(0);
        var params = {
            tumblrId: $('#tumblrId').val(),
            postId: $('#postId').val(),
            tagged: $('#tagged').val(),
            ptype: $('input[name="ptype"]:checked').val(),
            start: $('#start').val(),
            num: $('#num').val()
        };
        prevId = params.tumblrId;
        //console.log(params);
        //tumblrPosts.load(params);
        $.bbq.pushState(params);
        
        // Hide input form
        $('#showform, #navigation').show();
        $('#inputform').hide();
    });
    $('#first').click(function(e) {
        e.preventDefault();
        var pos = 0;
        $('#start').val(pos);
        $('#form').submit();
        window.scrollTo(0, 0);
    });
    $('#prev').click(function(e) {
        e.preventDefault();
        var start = parseInt($('#start').val());
        var num = parseInt($('#num').val());
        var pos = start - num;
        pos = pos >= 0 ? pos : 0;
        $('#start').val(pos);
        $('#form').submit();
        window.scrollTo(0, 0);
    });
    $('#next').click(function(e) {
        e.preventDefault();
        var start = parseInt($('#start').val());
        var num = parseInt($('#num').val());
        var end = tumblrPosts.tumblr['posts-total'] - num;
        var pos = start + num;
        pos = pos <= end ? pos : end;
        pos = pos > 0 ? pos : 0;
        $('#start').val(pos);
        $('#form').submit();
        window.scrollTo(0, 0);
    });
    $('#last').click(function(e) {
        e.preventDefault();
        var num = parseInt($('#num').val());
        var pos = tumblrPosts.tumblr['posts-total'] - num;
        pos = pos > 0 ? pos : 0;
        $('#start').val(pos);
        $('#form').submit();
        window.scrollTo(0, 0);
    });
    $('#toggleadvopts').click(function(e) {
        e.preventDefault();
        $('#advoptions').toggle();
    });
    $('#showform a').click(function(e) {
        e.preventDefault();
        $('#showform, #inputform').toggle();
    });
    $(window).bind('hashchange', function(e) {
        if (e.fragment === "") return;
        var params = e.getState();
        $('#tumblrId').val(params['tumblrId']);
        $('#postId').val(params['postId']);
        $('#tagged').val(params['tagged']);
        $('input[name="ptype"][value="' + params['ptype'] + '"]').prop('checked', true);
        $('#start').val(params['start']);
        $('#num').val(params['num']);
        //console.log(params);
        prevId = params.tumblrId;
        tumblrPosts.load(params);
        
        // Hide input form
        $('#showform, #navigation').show();
        $('#inputform').hide();
    });
    $(window).trigger('hashchange');
});
    </script>
</head>
<body>
    <div id="form">
        <div id="showform"><a href="#showform">Show input form</a></div>
        
        <form id="inputform">
            <label for="tumblrId" class="main">Tumblr ID:</label>
            <input id="tumblrId" class="main" name="tumblrId" size="8" value="fer1972">
             
            <input id="fetch" class="main" type="submit" value="Fetch!">
             
            <a id="toggleadvopts" href="#toggleadvopts">Toggle advanced options</a>
            
            <div id="advoptions">
                <label for="postId">Post ID:</label>
                <input id="postId" name="postId" size="4">
                 
                <label for="tagged">Tagged:</label>
                <input id="tagged" name="tagged" size="4">
                 
                <label for="start">Start:</label>
                <input id="start" name="start" value="0" size="2">
                 
                <label for="num">Posts:</label>
                <input id="num" name="num" value="10" size="2">
                <div class="grey">
                    <label>Type:</label>
                    <!-- text, quote, photo, link, chat, video, audio -->
                    <input id="type_all" name="ptype" value="" type="radio" checked="checked"><label for="type_all" class="plain"> All</label>
                    <input id="type_text" name="ptype" value="text" type="radio"><label for="type_text" class="plain"> Text</label>
                    <input id="type_photo" name="ptype" value="photo" type="radio"><label for="type_photo" class="plain"> Photo</label>
                    <input id="type_video" name="ptype" value="video" type="radio"><label for="type_video" class="plain"> Video</label>
                    <input id="type_audio" name="ptype" value="audio" type="radio"><label for="type_audio" class="plain"> Audio</label>
                </div>
            </div>
        </form>
    </div>
    
    <div id="images"></div>
    
    <div id="navigation">
        <a id="first" href="#first" class="navbutt">« First</a>
        <a id="prev" href="#prev" class="navbutt">< Previous page</a>
        <a id="next" href="#next" class="navbutt">Next page ></a>
        <a id="last" href="#last" class="navbutt">Last »</a>
    </div>
</body>
</html>

Leave a Reply