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.

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

  1. This is a great script. Very well written, worked great with a Sinatra powered site I'm developing. I don't like the bullets that it returns, and I have yet to see a great solution to that posted here, but I guess it gives me something to work on.

    You're a gentleman and a scholar, Remy. Keep up the great work.

  2. Perfect, exactly what i was looking for. Thanks for sharing!

  3. I'd have rathered the templates be done like
    template: '"%text%" %time%'
    Which would make it easier to customise, luckily it's open source so I fixed it myself.

  4. the script is super, but can anyone help me remove link fro time (that is 40 min ago, is clickable, i don't want that )
    please help

  5. one more request, i want an a twitter image inside the box around tweet (not avatar, ant custom image), how can i do that.

  6. Used the script in a webpage and the html is invalid, whether placed in the head/body. I'm using XHTML Transitional.

    Basically the template given in the example causes an error that says that specific elements (ie: span, a, div, em etc...) are not allowed in the that area of the page.

    How can I rectify that?

  7. @wrerm - just link to your JavaScript in an external script, or wrap the JavaScript in CDATA as such:

    <script type="text/javascript">
    <![CDATA[
    // content of your Javascript goes here
    ]]>
    </script>
  8. Is there an easy method of getting this script to only return tweets tagged with a specific hashtag?

    My javascript-fu isn't exactly strong, so any help would be appreciated!

  9. Hi, im also having problems getting my code to validate with XHTML transitional 1.0. Im wrapping the template elements in html tags directly like this:

    template: '<p class="bd">%text%</p><p class="src"><a class="time" href="http://twitter.com/%user_screen_name%/statuses/%id%/">%time%</a>&nbsp;&nbsp;&nbsp;&nbsp;from %source%</p>',

    is this the wrong way to go about this?

    Thanks in advance and thanks again for the great script.

  10. seems to ignore re-tweets... even when allow replies is enabled. :(

  11. On a secure site with a https address the script is triggering a 'non-secure items' error - any thoughts on how this can be fixed? Thanks

  12. Is there any way to change the id value from your username to a variable used in another function in javascript?
    I have a list of usernames on a database and it would be great to implement this code into a loop so that it can display the latest tweet of each username stored in the database.

  13. Thank you for the great step-by-step tutorial. It's been more then a week, that I've been looking for a simple tutorial to add my latest twitter updates to my site. With your tutorial it took me about 5 minutes to set it up.
    I have bookmarked this page + I have emailed the URL to my self + copied the URL to a word file and saved it on my desktop + and I have written down the URL in my notebook ;-)
    So thanks again for the great tutorial.

  14. great script!
    is it possible to import the twitter-feed from more than one user?
    i want to have a list whre meine tweets and the tweets from two friends are shown.
    thank you!

  15. This is an awesome script.

    The only problem I'm having is with the callback function. I'm trying to make the text change colour if there is a certain tag in the tweet. The problem is that the callback function is being called before the tweet is appearing.

    Any help would be appreciated.

  16. How to import twitter feed from users nin a specific country, eg Hungary or Finland?
    How to import feed in a specific language only, eg. portugese or german?

  17. Hi Remy,
    thanks for the excellent script! I have adapted it to the German date formats and made it available for download on my website. I hope you do not mind? ;-)

    kind regards,
    Markus

  18. I am the computer teacher at a school in Harlem where our kids will be building computers from scratch next week. There are 6 groups and I want each to use a twitter account to update their progress to their families. I love the content of these tips from REMY but cannot get it to work. The accounts are called build1csf, build2csf etc and the Web page I am trying to use is at http://www.cstorefront.org/build/index2.html ... clearly I am doing something wrong and I would love some help ... thanks in advance ... Steve ...
    sbergen@cstorefront.org

    p.s. using http://www.cstorefront.org/build/index.html I got 1 twitter account pulled in

  19. This replaces my previous comment which I submitted yesterday. With the tech of a friend Scott Wickham, I got your script working, Remy ... it is now posted at http://www.cstorefront.org/build and it works beautifully bringing in the twitter feeds from the 6 student twitter pages simultaneously ... thanks so much Remy for creating and posting this wonderfully useful script! Steve

  20. Great script. I have it set up... I just have a few questions. First, if using the automatically generated HTML, am I only limited to three variables? Second, is there a way to make the "30 minutes ago" clickable with the generated HTML? Third... is there a way to put quotation marks around the actual Tweet? I tried turning off "clearContents", but I still could never get the quotes to wrap. The site I have used this code on is clickable via my name.

Leave a Reply
Not required

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