Create a Twitter Feed with Attached Images from Media Entities

Create a Twitter Feed with Attached Images from Media Entities


Create a Twitter Feed with Attached Images from Media Entities
Our Sponsor: Sensational Jobs

Browse through dozens of job offers for web professionals including design jobs and tech jobs

Introduction

Twitter has added a new feature a while ago that I believe a lot of twitter users have been waiting for - Image Attachment. Also, not too long ago, I wrote a tutorial called Create a Dead Simple Twitter Feed with jQuery, one of the readers (Jamie Graham) asked about twitter media entities, well honestly, when I was building the script for the tutorial, I did not paid attention on the JSON data returned, I just grab what I need. I sat down and did a little bit of research, and I believe it'd be something fun to do so I made a second part of the twitter feed with jQuery.

This time, it will be a little bit more interesting, I modified my previous script and added some cool plugins, everything was done less than an hour, and it looks pretty good! I used my favourite modal window - FancyBox and masonry plugin in this tutorial. This is how it looks like:

UPDATE: I forgot to mention one thing! Twitter has rate limits. You can only call this API 150 times per hour per IP. The best way to solve this is using cache. So, instead of calling the API in $.ajax call, you get it from your server. A PHP is scheduled (a href="http://adminschoice.com/crontab-quick-reference">CRON Job to retrieve updated twitter feed in certain time and create the cache file once it's loaded. Don't worry, nettuts just released a tutorial about it :) How to Create An Advanced Twitter Widget

UPDATE: We have written an updated version of Twitter API tutorial based on Twitter Newest API 1.1. - Easiest Way to Retrieve Twitter Timeline and Hashtags


Create a Twitter Feed with Attached Images from Media Entities

HTML

The following is the HTML generate by Javascript, there are two different layout, one with image and one without. You can tweak the layout in twitter.js

 
<div id="jstwitter">
    <div class="tweet">
        Tweet Text here
        <div class="time">
			relative date here
        </div>
    </div>
 
    <div class="tweet">
        <a href="http://url" class="fancy"><img src="image path" alt="" width="150"></a> 
        Tweet Text here
        <div class="time">
			relative date here
        </div>
    </div>
    
    ......
    ......
    ......
    
</div>

CSS

Just a simple and clean CSS style to accomodate jQuery Masonry. It will be a 150px fixed width blocks.

 
#jstwitter {
	width: 80%;
	font-family: arial;
	font-size: 15px;
	color: #333333;
	padding: 10px;
	margin:0 auto;
}
 
#jstwitter .tweet {
	width: 150px;
	margin:5px;
	padding: 5px;
	float:left;
	background:#f1f1f1;
	border:3px solid #ddd;
}
 
#jstwitter .tweet a {
	text-decoration: none;
	color: #13c9d0;
}
 
#jstwitter .tweet a:hover {
	text-decoration: underline;
}
 
#jstwitter .tweet .time {
	font-size: 10px;
	font-style: italic;
	color: #666666;
}

Twitter JSON Data

Something you need to know about the JSON data returned by Twitter API:

  • Media contains array of objects, if you have more than one images attached in the tweet, the first image will be media[0], media[1] and so on. You probably need to use for loop to loop through it. In this tutorial we will grab the first image only.
  • This tutorial uses media_url, you also can use the https version called media_url_https.
  • 4 different image sizes: large, medium, small and thumbnail.
  • To retrieve different image size, for example, thumbnail, you need to use either media_url or media_url_https and append a colon plus the size

    eg: http://p.twimg.com/AQ9JtQsCEAA7dEN.jpg:thumbnail
    eg: http://p.twimg.com/AQ9JtQsCEAA7dEN.jpg:large

    You can test it on your browser.
 
"text": "#Photos on Twitter: taking flight http://t.co/qbJx26r",
"entities": {
  "media": [
    {
      "id": 76360760611180544,
      "id_str": "76360760611180544",
      "media_url": "http://p.twimg.com/AQ9JtQsCEAA7dEN.jpg",
      "media_url_https": "https://p.twimg.com/AQ9JtQsCEAA7dEN.jpg",
      "url": "http://t.co/qbJx26r",
      "display_url": "pic.twitter.com/qbJx26r",
      "expanded_url": "http://twitter.com/twitter/status/76360760606986241/photo/1",
      "sizes": {
        "large": {
          "w": 700,
          "resize": "fit",
          "h": 466
        },
        "medium": {
          "w": 600,
          "resize": "fit",
          "h": 399
        },
        "small": {
          "w": 340,
          "resize": "fit",
          "h": 226
        },
        "thumb": {
          "w": 150,
          "resize": "crop",
          "h": 150
        }
      },
      "type": "photo",
      "indices": [
        34,
        53
      ]
    }
  ],
  "urls": [
  ],
  "user_mentions": [
  ],
  "hashtags": [
  ]
 
}

Javascript

You will need to refer to my previous tutorial, Create a Dead Simple Twitter Feed with jQuery to understand hows everything work together.

We will integrate jQuery Masonry and Fancy box in this tutorial. Both of them will be activated once data are fully loaded.

 
JQTWEET = {
	
	// Set twitter username, number of tweets & id/class to append tweets
	user: 'quenesstestacc',
	numTweets: 20,
	appendTo: '#jstwitter',
 
	// core function of jqtweet
	loadTweets: function() {
		$.ajax({
			url: 'http://api.twitter.com/1/statuses/user_timeline.json/',
			type: 'GET',
			dataType: 'jsonp',
			data: {
				screen_name: JQTWEET.user,
				include_rts: true,
				count: JQTWEET.numTweets,
				include_entities: true
			},
			success: function(data, textStatus, xhr) {
 
				 var html = '<div class="tweet">IMG_TAG TWEET_TEXT<div class="time">AGO</div>';
				 var img;
				 // append tweets into page
				 for (var i = 0; i < data.length; i++) {
				
					//this is where we grab the image, only generate the HTML code if media entities were found in the JSON data
				try {
					if (data[i].entities.media) {
						img = '<a href="' + data[i].entities.media[0].media_url + ':large" class="fancy">';
						img += '<img src="' + data[i].entities.media[0].media_url + ':thumb" alt="" width="150" />';
						img += '</a>';
					} else {
						img = '';
					}
				} catch (e) {
					//e
				} 
					
					$(JQTWEET.appendTo).append(
						html.replace('IMG_TAG', img)
							.replace('TWEET_TEXT', JQTWEET.ify.clean(data[i].text, img) )
							.replace(/USER/g, data[i].user.screen_name)
							.replace('AGO', JQTWEET.timeAgo(data[i].created_at) )
							.replace(/ID/g, data[i].id_str)							
					);
										
				 }
				
				//trigger jQuery Masonry once all data are loaded				
				var $container = $('#jstwitter');
				$container.imagesLoaded(function(){
				  $container.masonry({
				    itemSelector : '.tweet',
				    columnWidth : 0,
				    isAnimated: true
				  });
				});		
				
				//the last step, activate fancybox 
				$("a.fancy").fancybox({
					'overlayShow'	: false,
					'transitionIn'	: 'elastic',
					'transitionOut'	: 'elastic',
					'overlayShow'	: true
				});							 					
				
			}	
 
		});
		
	}, 
	
		
	/**
      * relative time calculator FROM TWITTER
      * @param {string} twitter date string returned from Twitter API
      * @return {string} relative time like "2 minutes ago"
      */
    timeAgo: function(dateString) { 
		......
		......
		......
		
	}, // timeAgo()
    
	
    /**
      * The Twitalinkahashifyer!
      * http://www.dustindiaz.com/basement/ify.html
      * Eg:
      * ify.clean('your tweet text');
      */
    ify:  {
    
      //the purpose of hasIMG parameter is to remove all the unnessary links if there is images,
      //otherwise, parse link as usual
      link: function(tweet, hasIMG) {
        return tweet.replace(/\b(((https*\:\/\/)|www\.)[^\"\']+?)(([!?,.\)]+)?(\s|$))/g, function(link, m1, m2, m3, m4) {
          var http = m2.match(/w/) ? 'http://' : '';
          if (hasIMG) return '';
          else return '<a class="twtr-hyperlink" target="_blank" href="' + http + m1 + '">' + ((m1.length > 25) ? m1.substr(0, 24) + '...' : m1) + '</a>' + m4;
        });
      },
	
		......
		......
		......
	
	  //added hasIMG parameter
      clean: function(tweet , hasIMG) {
	      return this.hash(this.at(this.list(this.link(tweet, hasIMG))));
 
      }
    } // ify
 
	
};
 
 
 
 
// start jqtweet!
JQTWEET.loadTweets();

Conclusion

That's all. This is how it's done - display tweet with images. With jQuery and all the plugins out there, it really saves heaps of times to create something really simple but fancy in short time. Well, you need to know what you want to achieve first and understand how to use those plugins. We used Twitalinkahashifyer, relative time, fancybox and Masonry in this tutorial.

I hope you pick up something in this tutorial, hopefully able to help you in your upcoming project. Queness will continue to look for interesting and practical jQuery tutorials! Please help me to spread this tutorial to express your gratitude! :)

Author: Kevin Liew

Kevin Liew is a web designer and developer and keen on contributing to the web development industry. He loves frontend development and absolutely amazed by jQuery. Feel free to say hi to me, or follow @quenesswebblog on twitter.

Share the love

40 comments

Phong Thai @JavaScriptBank.com
Wed, 17th August 2011
very cool & good js tip, thank you very much for sharing. Reply
Kennedy
Thu, 3rd November 2011
Do you know if it possible to not only grab the images from twitter, but also yfrog.com & twitpic.com? If so how would I go about doing this? Reply
andrie
Thu, 10th November 2011
like kennedy said below me, how to grab images from yfrog and twitpic? Reply
Andrie
Thu, 10th November 2011
what i would also like to know is how can you resize and crop the image sizes. cause i need a cropped small size image instead of a low quality thumb. thank you. Reply
Andrie Muchtar
Thu, 10th November 2011
sorry for all the question, i was wondering how to display a twitter hashtag search instead of a usertimeline... Reply
Kevin Liew Admin
Thu, 10th November 2011
Not so sure how it would affect the current script, this is the API for it:

https://dev.twitter.com/docs/api/1/get/search Reply
Floyd
Thu, 5th January 2012
Hi, How about specific hashtags and not username? How could I apply this method? Thanks in advance! Reply
Kevin Liew Admin
Fri, 6th January 2012
Similar to below:
This is the API for it:
https://dev.twitter.com/docs/api/1/get/search

You will have to change the js according to the JSON structure Reply
Dale
Thu, 2nd February 2012
I'm still a little new at this, what parts exactly do you need to edit for this to only callback tweets containing the hashtag. I've found the JSON data for tweet entities here: https://dev.twitter.com/docs/tweet-entities
I'm assuming this gets placed in to twitter.js from your example. Does this get placed in Line 15? or line 28? I'd assume to ensure it only selects the Hashtag, we'd also remove lines 4, 6, & 15 correct? Reply
Kevin Liew Admin
Wed, 8th February 2012
It won't be this simple, I think the data return from JSON is different. Reply
Ed Penano
Sun, 15th January 2012
If I wanted to add images from either Instagram, how may I be able to do so? Also, is there a way to display search results? Thank you for your time! Reply
dragan
Sun, 11th March 2012
How I can to ban tweet without images? Reply
Kevin Liew Admin
Mon, 19th March 2012
You can hide them:

if (!img) {
$(JQTWEET.appendTo).append(
html.replace('IMG_TAG', img)
.replace('TWEET_TEXT', JQTWEET.ify.clean(data[i].text, img) )
.replace(/USER/g, data[i].user.screen_name)
.replace('AGO', JQTWEET.timeAgo(data[i].created_at) )
.replace(/ID/g, data[i].id_str)
);
}

but then, you total tweet mine be affected because some are not showing. Reply
Justis
Tue, 3rd April 2012
How can one implement a hashtag search for both images and tweets.....its hard implementing it, I could use with some guidelines . Reply
jeffry
Tue, 1st May 2012
How to display the home feed based on hashtags? this script is awesome! Reply
lmk
Mon, 14th May 2012
How to get twitter feed images?? Reply
Michael
Mon, 14th May 2012
Hi there,

Thanks for the article. This is great!

Quick question- how can this code be modified to work with images that are stored on yfrog? instead of the pic.twitter.com URL they have a t.co URL that directs to a yfrog picture. Please help!

Thanks!
Michael Reply
himanshu
Wed, 16th May 2012
very good js.thank u for sharing. Reply
MeltingDog
Sun, 10th June 2012
Thanks for this!
I was wondering if there was a proper way to take the <a> tags off the images?

If I remove:

img = '<a href="' + data[i].entities.media[0].media_url + ':large" class="fancy">';

I get an error.

Thanks! Reply
Kevin Liew Admin
Wed, 13th June 2012
Just remove line 30. Reply
Andrew
Fri, 22nd June 2012
Thank you for this tutorial, it was working before but now it stopped. My guess is that something changed with twitter API. Is it possible to get an UPDATE for this? I spend myself doing the research but author should know the best ;) Reply
Kevin Liew Admin
Wed, 27th June 2012
It's fixed, please refer to comment above. I have updated the tutorial also. Reply
Alex
Wed, 27th June 2012
Thanks this is great!

But after it displays the first 3 tweets I get this message in the console:
Uncaught TypeError: Cannot read property 'media_url' of undefined

Reply
Kevin Liew Admin
Wed, 27th June 2012
Im not sure what's happening, but I think Twitter has changed its API because you're not the only one. Andrew (below) is having the same problem.

I actually had a look, and played with it, I can't seem to able to sort it out now. Reply
Alex
Wed, 27th June 2012
I changed line 28 to:

if (data[i].entities.media && data[i].entities.media.length > 0) {

and it seems to be ok Reply
Kevin Liew Admin
Wed, 27th June 2012
Alright, yep. I found a fix also.

I put try { } catch (e) { } around it. That fixes it as well. Reply
Kevin Liew Admin
Wed, 27th June 2012
They must have slightly changed the JSON data. Oh well, I should have put a test to ensure there is data anyway. :) Reply
Kieran
Sat, 21st July 2012
Thanks for a great article, works really well.

I was wondering if you knew how to make the links from the tweettext open in an iframe somewhere on the same page so people don't leave the page?

Many Thanks Reply
Kevin Liew Admin
Mon, 23rd July 2012
Line 102: else return '<a class="twtr-hyperlink" target="_blank"

You can change the target to the name of the iframe. Reply
Ben
Sun, 29th July 2012
thanks for your great tutorial!

I've been looking on how to display the latest images of a certain user on my website.. I guess this is the only way? Or is there a specific API-method I could use to only retrieve the "latest images" of a user? (like the ones you see on a twitter page on the left-hand side) Reply
Andrew Jones
Wed, 8th August 2012
This is great, but for some reason it repeats some images on tweets that actually have no images associated with them? Reply
Anders
Tue, 18th September 2012
Thanks.... Is it possible to display Image and hyperlink ? Reply
Anders
Tue, 18th September 2012
Thanks. Is it possible to display image and link? Reply
Adam
Mon, 1st October 2012
Great tutorial. I was wondering if there is a way to grab a hashtag as well as a user? Reply
tatters
Thu, 29th November 2012
Has anyone found a solution to display tweets and photos based on a #hashtag(s)? Would be an awesome update if possible. Thanks Reply
Patrick
Mon, 4th February 2013
Trying to get this to work in Opera (both the demo page and my page are not displaying anything but works fine in other browsers) with no luck any idea, is it an issue with jquery? Reply
Arlex
Wed, 15th May 2013
Amazing stuff! Due to my noobness I'm gonna dare and ask: Is there a way to display only video- and picture-flagged tweets into a tweeter feed? If so, is there an extension or app to do that? I really don't know where or how to look for something like that.

Thanks in advance. Reply
chirag
Wed, 12th June 2013
Hi there,

I have integrate your twitter feed plugin in my client's website and was working really nice but today its not working at all.

You can check here.

http://www.myextensionz.com/ ( on right of facebook feeds )
http://www.myextensionz.com/ ( on left of facebook feeds)

Please check and give me asap.

Thanks

Chirag Reply
patrick
Fri, 21st June 2013
Did twitter api's change all of mine and the demo ones stopped working? Reply

Leave a Comment

Please keep in mind that comments are moderated and rel="nofollow" is in use. You can use [code][/code] if you want to write codes. Don't spam us :) Thanks!

Advertisement