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. @jordan: How did you get this to work for multiple users' timelines? Very cool!

  2. Nice. I have started using your script on my site and it works well. My only problem is that its brake the validation if I use template. The validator find then an error: document type does not allow element "a" here. I understand the proplem, but can't find a solution.

    Thanks in advance

  3. Excellent - well wrapped up, been looking for a concise explanation for some time. Thanks.

  4. I'm with adam! A response would be awesome!

    I'm desperately trying to display two unique twitter accounts on the same webpage (not blog). And every script I've tried comes out as this homogonized mess of one twit with both accounts melded together. Why does something so seemingly simple have to be so painful?

  5. Also, you might want to check the code on this page. You have a busted link:

    id: your screen name on Twitter, for example mine is "<a href="http://twitter.com/rem"

    it should be (?):

    id: your screen name on Twitter, for example mine is "http://twitter.com/rem

  6. @sie & @adam - this page has two twitter requests going on (one in the header and one in the example). Equally if you want two different accounts - or more than two for that matter, have you tried the examples in the zip file?

    http://code.google.com/p/twitterjs/downloads/list

    There's an example showing three different accounts. Very simple, just repeat the call.

  7. my site was displaying "Warning: SimpleXMLElement::__construct() [simplexmlelement.--construct]: Entity: line 10: parser error : Opening and ending tag mismatch:" errors from a php twitter script I had installed to simply pull my last tweet. In googling the error, there are a TON of people's cached sites out there with the same error. Something must have changed on the Twitter side? Or it was always there, but intermittent? Regardless, your script saved the day and is much sexier. Rock on.

  8. Is there a way for me to send a reply back?

  9. Any way to display last entries containing a given hashtag, instead of an account id ?

  10. Has this ever been successfully integrated within a secure site (https)? I was looking to utilize this to serve Twitter Comments to Intranet users who would otherwise be blocked via outbound proxy blacklisting of Twitter from the workplace network. I have been successful in altering the Twitter "http" links to "https" within the JS files to remove the "unsecure content w/in a secure site" warnings, However the called Twitter content would only display in IE7 & 8 browsers whereas Firefox / IE6 / Chrome will only continue to display the "wait" message...

  11. I use the codes and they work great, I'm trying to learn some styling details. For instance being able to have alternating tweets in a different background color to more clearly separate them, or divide them with a solid line like the blink182 site. Also, this is slightly more of a priority to me, how do you not have the bullet's show up?

    on mine it throws a bullets up.

    I'm new to javascript and coding in general, but check out my site to reference what I'm talking about. lcchaven.org thank you.

  12. Nevermind actually, with some fiddling around I finally got it. However scope the site if you are interested :)

    Thanks for learning code :) and making one that works.

  13. This is exactly what I was looking for and I wish I had found it sooner instead of looking through all the various widgets and scripts out there that do an assortment of other things except just display your latest twitter posts.
    Thanks for developing this JS!

  14. Excellent, there's so many over complicated solutions out there so finding this was great!

  15. is there a way to have the content refresh after x min or x seconds?

  16. Hi,
    Is there a way to make the first tweet in a bigger font than the rest... just like it displays in your twitter.com page?

    Thanks.

  17. great stuff and i tried to use your script like on your server you linked to (http://remysharp.com/wp-content/uploads/2007/05/twitter.js) but i see the hash tags aren't include. Is there a possible chance you'll addapt this script ?

    I don't like how the new date appearance is in the scripts on google code, i really like it like yours with the mention of days ago and not by hours.

    I tried it myself but got stuck.

    thx in advance !

  18. Is it possible to filter out (not display) Twitter updates that start with certain words? I want to start using TwitterFeed to send Twitter updates when I write a new blog post. It will unfortunately populate my embedded Twitter timeline (beautifully embedded through your script!) with updates beginning "New article: ...." If you're on my site reading the embedded timeline, you don't need to see that there's a new article. Plus, since I'm only showing 5 updates, I don't want half of them to be "New article: ...."

    So, it would be very cool if I could have the embedded timeline ignore updates that begin "New article: ...."

    Thanks for this great script!

  19. @Dries - you shouldn't really link directly to my own hosted version, because I could remove it or change it and break your site at the same time. Use the one hosted on Google, then you'll get the latest version:

    http://twitterjs.googlecode.com/svn/trunk/src/twitter.min.js (also contains hashtags being linked up)

  20. Remy: Thank you for the response regarding having multiple accounts/timelines on the same page. I realize you can make multiple calls and have multiple occurrences. But is there a way to mix the timelines so that they sort together as one timeline of various people? In other words -- one time-sorted timeline drawing from multiple accounts?

Leave a Reply
Not required

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