Themeforest

jQuery Tutorial – Create a Pinterest Feed jQuery Plugin Using AJAX & jQuery Isotope

jQuery Pinterest Feed Plugin Tutorial

In our latest jQuery social network tutorial we are going to create a jQuery plugin to display Pinterest feeds via AJAX from either a username or pinterest board and display them in a masonry style wall using jQuery Isotope.

The plugin will also include code to display time since posted, options to set the number of feed items to display plus Facebook and Twitter share links to help boost the traffic to your pins.

View jQuery Pinterest Feed Plugin DemoDownload Demo Source Files

The Pinterest Feed Plugin Options

  • id – this is where the username or pinterest board will be added when initialising the plugin
  • results – set the number of pins to display
  • tweetId – set the twitter username for share links

The Pinterest Feed Plugin Components

  • AJAX function that will load the pins from a Pinterest RSS feed.
  • A function that will convert the Pinterest post date to a relative “time since” date.
  • A function that will add both Facebook and Twitter share links & open in popup window.
  • A function to generate the wall layout using jQuery Isotope.

The Plugin Code

Since Pinterest have not yet released their latest API (at time of post) we are going to use their public RSS feeds to create the wall along with the Google Feed API, which makes it easier to download RSS feeds using jQuery/javascript.

We are using a standard jQuery pattern to create the plugin. See comments in plugin code for more information on each section:

(function($){

	PinterestFeedObject = function(el, options) {
		this.create(el, options);
	};

	$.extend(PinterestFeedObject.prototype, {

		create: function(el, options) {

			// Set the default options
			this.defaults = {
				id: '', // enter username, pinterest list ID or search keyword
				results: 10, // number of results to display
				tweetId: '' // twitter username for share links
			};

			var o = $.extend(true,this.defaults,options);

			// Add ul tag to target element
			$(el).append('<ul class="stream"></ul>');

			// Set Pinterest RSS url using Google Feed API
			var cp = o.id.split('/'),
				ext = cp.length > 1 ? '/rss' : '/feed.rss',
				href = 'http://www.pinterest.com/'+o.id,
				url = 'http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num='+o.results+'&callback=?&q=' + encodeURIComponent(href+ext);

			// jQuery AJAX call
			jQuery.ajax({
				url: url,
				cache: true,
				dataType: 'jsonp',
				success: function(a){
					a = a.responseData.feed.entries;
					$.each(a, function(i,item){
						if(i < o.results){
							var d = item.publishedDate,
								img = '<a href="'+item.link+'"><img src="'+$('img',item.content).attr('src')+'" alt="" /></a>',
								html = '<li>' + img + item.contentSnippet;

							// Add share links
							html += '<span class="section-share">'+shareLink(item.contentSnippet,item.link,o.tweetId)+'</span>';

							// Get time since
							d = d != '' ? html += '<span class="date">'+nicetime(new Date(d).getTime())+'</span></li>' : '' ;
						}

						// Add pinterest feed items to stream
						$('.stream',el).append(html);
					});
				},
				complete: function(){

					// Code to open new popup window for share links + open other links in new browser tab
					$('.stream a',el).click(function(e){
						if($(this).parent().hasClass('section-share')){
							var u = $(this).attr('href');
							window.open(u,'sharer','toolbar=0,status=0,width=626,height=436');
							return false;
						} else {
							if(external){this.target = '_blank';}
						}
					});

					// jQuery Isotope function
					var $c = $('.stream',el);
					$c.imagesLoaded( function(){
						$c.isotope({itemSelector : 'li'});
						$('li',$c).fadeIn();
					});
				}
			});
		}
	});

	$.fn.dcPinterestFeed = function(options, callback){
		var d = {};
		this.each(function(){
			var s = $(this);
			d = s.data("pinterestfeed");
			if (!d){
				d = new PinterestFeedObject(this, options, callback);
				s.data("pinterestfeed", d);
			}
		});
		return d;
	};

	// Creates facebook & twitter share links
	function shareLink(st,sq,tweetId){
		var sq = encodeURIComponent(sq), st = encodeURIComponent(st);
		var s = '<a href="http://www.facebook.com/sharer.php?u='+sq+'&t='+st+'" class="share-facebook"></a>';
		s += '<a href="https://twitter.com/share?url='+sq+'&text='+st+'&via='+tweetId+'" class="share-twitter"></a>';
		return s;
    }

	// Function to convert date to relative date
	function nicetime(a){
		var d = Math.round((+new Date - a) / 1000), fuzzy;
		var chunks = new Array();
			chunks[0] = [60 * 60 * 24 * 365 , 'year'];
			chunks[1] = [60 * 60 * 24 * 30 , 'month'];
			chunks[2] = [60 * 60 * 24 * 7, 'week'];
			chunks[3] = [60 * 60 * 24 , 'day'];
			chunks[4] = [60 * 60 , 'hr'];
			chunks[5] = [60 , 'min'];
		var i = 0, j = chunks.length;
		for (i = 0; i < j; i++) {
			s = chunks[i][0];
			n = chunks[i][1];
			if ((xj = Math.floor(d / s)) != 0)
				break;
		}
		fuzzy = xj == 1 ? '1 '+n : xj+' '+n+'s';
		if (i + 1 < j) {
			s2 = chunks[i + 1][0];
			n2 = chunks[i + 1][1];
			if ( ((xj2 = Math.floor((d - (s * xj)) / s2)) != 0) )
				fuzzy += (xj2 == 1) ? ' + 1 '+n2 : ' + '+xj2+' '+n2+'s';
		}
		fuzzy += ' ago';
		return fuzzy;
    }

})(jQuery);

To make it easy to use copy the above plugin code into a file and name it jquery.pinterest.feed.js.

Using Your jQuery Pinterest Feed Plugin

1. Add the jQuery Library, jQuery Isotope & Pinterest Plugin

Add the plugin link, link to the jQuery Isotope plugin & link to the jquery library to the document head:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.isotope.js"></script>
<script type="text/javascript" src="js/jquery.pinterest.feed.js"></script>

2. Initialise the jQuery Pinterest Feed Plugin

The minimum options required are the id for your pinterest feed and the tweetId for the share links. There are 2 options for the id:

  • To show a feed from a Pinterest username just enter the username – e.g. “jaffrey”
  • To show a feed for a Pinterest board enter the username + “/” + board slug, which you can get from the Pinterest board URL – e.g. “jaffrey/movies-to-watch”

To initialise the plugin add the following code in your document head after the links to the plugin file and the jQuery library:

<script type="text/JavaScript">
    $(document).ready(function() {
        $('#pinterest-feed').dcPinterestFeed({
            id: 'jaffrey',
            tweetId: 'designchemical'
        });
    });
</script>

To change the number of results:

<script type="text/JavaScript">
    $(document).ready(function() {
        $('#pinterest-feed').dcPinterestFeed({
            id: 'jaffrey',
            tweetId: 'designchemical',
            results: 20
        });
    });
</script>

3. The Pinterest Feed CSS

The styling for the wall is fairly easy – create the drop-shadow for the feed items, position the date and create the Twitter & Facebook share links using a css background sprite (included in demo download files):

ul.stream li {
	display: none;
	width: 195px;
	margin: 0 6px 12px 6px;
	background: #fff;
	font: normal 13px/18px Arial, sans-serif;
	color: #333;
	position: relative;
	padding: 10px 15px;
	-webkit-box-shadow: 0 1px 2px rgba(0,0,0,0.5);
	-moz-box-shadow: 0 1px 2px rgba(0,0,0,0.5);
    box-shadow: 0 1px 2px rgba(0,0,0,0.5);
}
ul.stream li img {
	padding: 1px;
	background: #fff;
	border: 1px solid #ececec;
	margin: 3px 0 5px 0;
}
ul.stream li .date {
	display: block;
	clear: both;
	margin: 10px 0 0 0;
	line-height: 12px;
	color: #666;
	font-size: 11px;
	font-style: italic;
}
ul.stream li .section-share {
	bottom: 8px;
    right: 15px;
    position: absolute;
	z-index: 2;
}
ul.stream li .section-share a {
	display: block;
	width: 16px;
	height: 16px;
	float: left;
	margin: 0 2px 0 0;
	background: url(images/share.png) no-repeat 0 0;
}
ul.stream li .section-share a.share-twitter {
	background-position: 0 -16px;
}
ul.stream li .section-share a.share-facebook:hover {
	background-position: -16px 0;
}
ul.stream li .section-share a.share-twitter:hover {
	background-position: -16px -16px;
}

4. The HTML

The only HTML required in your page is an empty div tag with the ID set to the same as that used in the initalisation code – e.g. pinterest-feed:

<div id="pinterest-feed"></div>

Just place the above tag in your page between the body tags where you want the Pinterest wall to appear.

Show Multiple Pinterest Walls Per Page

The plugin can show multiple feeds per page, as shown in the demo. To do this just add multiple div tags with unique IDs and enter the initialisation code – e.g:

jQuery Code

<script type="text/JavaScript">
$(document).ready(function() {

    $('#pinterest-feed-1').dcPinterestFeed({
        id: 'jaffrey',
        tweetId: 'designchemical'
    });

    $('#pinterest-feed-2').dcPinterestFeed({
        id: 'jaffrey/movies-to-watch',
        tweetId: 'designchemical',
        results: 20
    });
});
</script>

HTML Code

<div id="pinterest-feed-1"></div>
<div id="pinterest-feed-2"></div>

View jQuery Pinterest Feed Plugin DemoDownload Demo Source Files

Credits

5 Comments

  • Just curious – is there a way to pull in the board COVER image, instead of the most recent pins to that board?

    • Unfortunately Pinterest dont include that information in their feeds at the moment

  • [...] Create a Pinterest Feed jQuery Plugin Using AJAX & jQuery Isotope – In this tutorial we are going to create a jQuery plugin to display Pinterest feeds via AJAX from either a username or pinterest board and display them in a masonry style wall using jQuery Isotope. [...]

  • Hi,

    Really dig the tutorial, am experimenting with it on my local system. Everything appears to be working correctly and I love the isotope layout as opposed to a standard grid.

    One thing I’m finding is that the feed doesn’t seem to update to newer images. I added new images to my pinterest account yesterday, but they aren’t displaying today -even on page reload. Are there some caching parameters I can adjust?

    Thanks.

    • Hi,

      Pinterest dont update their public feeds immediately.

Leave a comment

To add code to your comments wrap the code text in [text][/text] tags