Check out my latest project: Full Frontal JavaScript Conference

Add Twitter to your blog (step-by-step)

Update - updated 25-Aug 2009

You can now directly hotlink from Google to remain up to date without having to change your script, see code below.

Hotlink from Google

<script 
  src="http://twitterjs.googlecode.com/svn/trunk/src/twitter.min.js"
  type="text/javascript">
</script>

Download to self host

Download latest Twitter.js

Following on from how to add Twitter without hanging your blog, as requested, here is a step-by-step guide to adding Twitter to your blog without it hanging your web site.

Below is a working example of loading twitters after the page has completed, thus preventing the whole page from locking up (notice that the spinner will continue until the twitters are loaded) - based on my tweets from myself:

Please wait while my tweets load

Using my twitter.js script.

Options

The function tags the following parameters:

  • CSS id of target element
  • Settings object (details below)

Settings object:

  • id: your screen name on Twitter, for example mine is "rem"
  • count: number of twitters you want, defaults to 1.
  • clearContents: if you have content in the container you may want to clear it. Defaults to true.
  • enableLinks: true/false - scans the tweet for a link and makes it clickable, includes @replies and #hashtags, by default is true.
  • ignoreReplies: true/false - skips over tweets starting with @. If requesting 1 tweet, and this flag is set, behind the scenes it will request 2 in case the first starts with @ - but if the 2 most recent are replies, nothing will be shown.
  • currently disabled withFriends: true/false - whether to include friends tweets. Defaults to false.
  • template: the HTML template to use within each li element. See below for template variables.
  • prefix: if not using a template, you can use this. If you want to prefix each twitter, add here, e.g. 'Remy said'. Note that you can use template variables in this field.
  • timeout: Number of milliseconds before triggering onTimeout. If onTimeout is set, timeout defaults to 10 seconds.
  • onTimeout: Function to call when timeout is reached. Context is set to HTML element tweets were going to be inserted into.
  • onTimeoutCancel: true/false - if not set, the timeout can trigger, but then the Twitter script could complete and override the cancel. To avoid this, set onTimeoutCancel = true. Defaults to false.
  • newwindow: true/false - if set to true, all links in tweets (and otherwise) will open in a new window. Defaults to false.
  • callback - Function to call when the twitter render is completed. Doesn't fire if the script times out.

For example:

getTwitters('tweet', { 
  id: 'rem', 
  count: 1, 
  enableLinks: true, 
  ignoreReplies: true, 
  clearContents: true,
  template: '"%text%" <a href="http://twitter.com/%user_screen_name%/statuses/%id%/">%time%</a>'
});

Template variables

All variables should be wrapped in % symbols (see the above example).

  • text - the actual status message
  • id - id of status message
  • source
  • time - relative 'friendly' time
  • created_at - raw time
  • user_name - real name
  • user_screen_name - username
  • user_id
  • user_profile_image_url - avatar
  • user_url - home page
  • user_location
  • user_description

Container HTML

You need to insert a holder element for the twitters to go in to. In the example above, I've included some 'waiting to load' content - but you don't have to.

Here's what I did:

<div id="tweet">
 <p>Please wait while my tweets load <img src="/images/indicator.gif" /></p>
 <p><a href="http://twitter.com/rem">If you can't wait - check out what I've been twittering</a></p>
</div>

Here are some more progress indicators.

If you include contents inside the holder div, then you'll need to set the 'clearContents' flag.

Add the script

You can download the twitter.js script or you can hotlink directly from the Google code repository (as seen in the example below).

Add the following code within the head or (best at the bottom of the) body tag:

<script 
 src="http://twitterjs.googlecode.com/svn/trunk/src/twitter.min.js" 
 type="text/javascript">
</script>
<script type="text/javascript" charset="utf-8">
getTwitters('tweet', { 
  id: 'rem', 
  count: 1, 
  enableLinks: true, 
  ignoreReplies: true, 
  clearContents: true,
  template: '"%text%" <a href="http://twitter.com/%user_screen_name%/statuses/%id%/">%time%</a>'
});
</script>

(this example will generate my twitter status in quotes on a single line with the 'ago' linkable back to the original twitter post)

Note that the getTwitters function will execute after the page has been loaded by your browser. It will fire once the DOM is loaded but before images are loaded.

Styling

If you don't use a template, then the HTML is generated for you.

Each block of text is contained with in a span and includes it's own class, e.g. the HTML generated would look like this:

<div id="tweet">
  <ul>
    <li>
      <span class="twitterPrefix">Remy said: </span>
      <span class="twitterStatus">I just had a bizarre spaces moment - moving my cursor to the bottom of the screen switched space - annoying if it hadn't just gone away.</span>
      <span class="twitterTime">20 minutes ago</span>
    </li>
    <li>
      <span class="twitterPrefix">Remy said: </span>
      <span class="twitterStatus">Great quote - Michael J Fox: "my happiness grows in direct proportion to my acceptance, and in inverse proportion to my expectations."</span>
      <span class="twitterTime">7 days ago</span>
    </li>
  </ul>
</div>

So each block of content is targetable using CSS to style the way you wish.

Comments, feedback or suggestions will be more thank welcome.

405 Responses to “Add Twitter to your blog (step-by-step)”

  1. Hey Remy, thanks for the great script. Quick question though: When a tweet is posted from somewhere other than twitter (ie. Facebook) it adds a link at the end of the post as a source... it looks something like " http://bit.ly/xxxxx". Is there any part in your script that can mask that as something else like "Read more..." for example?

  2. Hi,

    First => great script! but I am trying to get the results without the ul and li wraps. Is there a script or way that they will not be added?

    Thanks

  3. You are a true gent. This code is dead easy to use even for a total Java noob.

  4. hi Remy, the script works like a treat but am i wrong in assuming that the container should refresh itself automatically? if so, i can't get the feed container to refresh automatically and display the latest tweets automatically. am i missing a setting?

    thank you.

  5. I dig this script, but its not working in Firefox browsers. It just keeps the "holder" message.

  6. Hi, Remy. Great script!!
    I'm trying to use it in that URL: http://www.observa.com.uy/defaulttw2.asp, and it loads fine the last 20 tweets. But it doesn't reload automatically. I have read all the comments of that post and I understand it should do it, and if it doesn't you have told it may be a Twitter server issue.
    But I have tried in an other URL (www.observa.com.uy/defaulttw.aspx) using both at the same time, the widget of Twitter and your script. The first one refresh automatically a few seconds after the tweet is submited, but your script doesn't.
    I'd really appreciate if you could take a look and tell me what am I missing or doing wrong.
    Thanks a lot

  7. I made a mistake with the first URL I wrote.
    Is http://www.observa.com.uy/defaulttw2.aspx

  8. @jovenolo - nope, it's not supposed to reload automatically. Sorry for the confusion. I do know of a twitter plugin that will support that, I'm likely to announce it via my twitter stream.

  9. Hi,
    Script works great thanks! But i dont see a preloader? How do i implement this?

  10. Hey -- Look what three hours and your script just did for my website:

    http://pocagentesabe.com/martin

    Thanks !

    PS: It'd KILL if you could enumerate each tweet / li element in order to apply different templates to each -- Or at least separate the newest one from the rest, so we could make it bigger, just like Twitter does on one's profile page.

  11. Great script, thanks.

    I have a question.. how can I force a _blank target on the links in a twitter post? Thanks.

    -jb

  12. Great script but I have two suggestions that would make it killer. Can you add a way to add multiple twitter accounts that you want in a stream and also #hashtags ?. Also how can I modify the code to be triggered from a function as opposed on page load? I want to be able to refresh and trigger the streams without having to refresh the page.

    Thanks in advance.

  13. this code works GREAT!!! thanks so much remy for sharing! im absolutly stoked!

  14. hi! it is awesome!

    but i have one question - how to make twitter integration with hashtag instead of username? I want to show twitter messages on the page not from one user, but from the hashtag.

    thanks.

  15. can anyone help with sample code to get tweets from list?

  16. Yeah, I'd really love to be able to display based on hashtag, as well. I tried sticking in something like #search?q=%23steven, but it didn't work.

  17. Is there a filtering method available? I noticed that LinkedIn has an option only to display messages starting with #in.

    What's the trick?

  18. I have the template variable: geo_enabled: true, and %geo% in the template which is either revealing "null" or "[object Object] " depending on whether a tweet is geolocated.

    What I would like to do is reveal the 52.02345822 -2.5008273 data in the rss stream and wrap it in an icon to link to my map (where the geolocated tweets are being displayed). The location information within the url passed, would be parsed by the map code.
    Cheers.

  19. @Paul R.
    I worked it out, check my code, it's pure CSS - I didn't even touch Gery's script:

    #tweet a {display:inline-block; width:110px; height:20px; background:url('../img/index/tweet_more.png');font-size:0;}

    It finds links in tweet stream, changes their font size to zero (so they theoretically disappear but still stay in stream). As you can see, there is still a clickable area with custom background. :)

    Hope I helped.

    Gery, great script, one of the best I've ever seen. :)

  20. For everyone who wants auto-refreshing feeds, it's pretty easy to do this yourself thanks to the 'callback' option... here's a quick (tested) example of how it can be done. Just wrap your normal call to getTwitters() with something like this:

    var myTweets = {
      'delayedRefresh' : function() {
        setTimeout(myTweets.refresh, 30 * 1000); // refresh twitters every 30 seconds
      },
      'refresh' : function() {
        getTwitters('twitterFeed', {
          id: 'somebody',
          count: 10,
          callback: myTweets.delayedRefresh
        });
      }
    };
    myTweets.refresh();
    
Leave a Reply
Not required

CODE: Please escape code and wrap in <pre><code>, doing so will automatically syntax highlight