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. [...] Add Twitter to your blog (step-by-step) (tags: twitter javascript web web2.0 blog programming wordpress) [...]

  2. Many, many thanks - this is JUST what I was looking for :)

  3. With the addition of friends and the template driven output this is really quite fantastic.

  4. I love the script! It's just what I was looking for. Thanks for sharing! Brilliant work!

    Kind regards.

  5. @Piotr - I see from your web site you've reverted back to 1.2 of Twitter.js. Is the new ones not working for you? If you have an example, I don't mind taking a look.

  6. Remy, this is a newbie question. Where do I upload the script to? The theme root or the website root?

  7. @Koka - it doesn't really matter, but if you want to keep things really simple, stick it in the root of your web site (usually htdocs) and refer to it as /twitter.js

  8. Absolutely brilliant. The solution to a problem I've had for a good while.Thank you so much!

  9. [...] Tools for regular Twitter digest posts and built-in posting from WP, and a combination of twitter.js and the Twitter Widget for my sidebar [...]

  10. Hey, thanks for this. However, I don't want the resulting information to be within ul and li tags. I'm only telling the function to give me 1 update, and the reason is I want to put it within a p tag, but it keeps giving me an li tag no matter what. I've spent two hours trying to figure out how to do this to no avail and I'm going insane. I would really appreciate if you could help me with this, please.

  11. [...] Add Twitter to your blog (step-by-step) Linked is a working example of loading twitters after the page has completed, thus preventing the whole page from locking up. [...]

  12. Hello, it's a cool app, but i have a question.
    We have a community blog and we would like to show all of our editors' twits (1 from each). How can i manage this, because this js just show the last one. Is there any easy way to implement it? Thanks.

  13. @Isti - yep it does support exactly what you want.

    Just use the script entry each time with a different id and username.

    You can see a working example on this page, note the single tweet in the header of the blog, and the list in the blog post.

  14. Where do you call the first getTwitters function? (below the title)

    I promise this is my last question, please answer me! Thanks ;)

  15. @Isti - no problem :-)

    The first one is being loaded from my [theme]/js/main.js script - which is basically my bootup script.

    Here's another example of two tweet functions running on the page for different users

  16. Thank you very much!

  17. Wow, nice in depth article, I have been thinking of integrating Twitter into my sidebar, I will definitely have to use this technique, when I do. Thanks!

  18. Remy, this is a wonderful script and very useful but I have one issue with it. Including an <a href tag in the template section stops the page from validating. I use the script like so:

    template: '<a href="http://www.twitter.com/dragindb">Paul is %text%...</a>'

    The only way to get it to validate is to remove the a tag. I think to solve the problem, at least in my case, the a tag could be output through the .js file. Unfortunately my javascript skills are severely lacking. What do you think? Do you have any other ideas?

  19. @Paul - two different ways are available:

    1) split out the string like this:

    template: '<' + 'a href="http://www.twitter.com/dragindb">Paul is %text%...<' + '/a>'

    2) Or put your JavaScript in a separate file and import it via a <script src="xyz.js" ></script>

  20. Is it possible to refresh the displayed Twitters every 5 minutes or so? I tried to call the getTwitters function with a setTimeout, but this doesn't seem to work.

Leave a Reply
Not required

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