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. Thanks for this great script. Using it on my Tumblog to great effect (wrapped the entire Twitter subsection into the script so if it times out, nothing displays at all and no one is the wiser).

  2. This is very useful indeed. The majority of twitter inclusions are for WordPress. Great stuff!

  3. Great code!!!! One thing though the spinner.gif keeps looping an never goes away even after the tweets have been displayed. What have I done wrong?

  4. great script remy. its working great on my site. i was wondering whats the limit per hour for this script? what about oauth for a higher limit? please advise. thanks

  5. thanks it's working, but the time is not accurate from twitter site :(

  6. very usefull, thank you!

    -Politiet i Danmark

  7. Great script, one of the fastest ones I've seen for twitter. Quick question though... is there anyway to add an alternate option in case you want each entry to be styled differently?

    For instance:
    li span1 {
    background: #FFF none;
    color: #000;
    }
    li span2 {
    background: #CCC none;
    color: #000;
    }

    This way each tweet can easily be read without having to add padding to the bottom of the list css to separate.

  8. Great code Remy, I use it a long time ago !!!

    @ Gillian,

    Oh, it should be nice to post only the tagged twitts ! Is there anybody to work on it ?
    I tried to change the code @user reply by #tag but no success....

    An idea ?

  9. @ryan

    The time isn't incorrect, it's just the wrong time zone.

    I THOUGHT I had found the place to modify the js, but apparently I was wrong... or did something silly.

    and about line 100 there is a pice of code

    timeSpan.innerHTML = relative_time(obj[i].created_at);

    which I thought I could modify to hardcode a GMT -5 time into it. Apparently I was wrong, or, like I said, did something silly.

    Once I figure out a quick fix, i'll post it. Maybe a custom time zone can be a feature in the next update. it's a pretty quick fix.

  10. ok so after reading through the code, at the bottom near lines 270 to 350-ish, I can see that the code is actually trying to get the browser's local time and adjust the displayed time accordingly.

    I'm trying to figure out why this isn't working.

    For example, I wrote a post (according to twitter) at 9:55 pm local time. I live in GMT -5 time (Toronto).

    On my blog, I get 1:55 am, which is 4 hours too late. My guess as to why it's 4 hours off instead of 5 is probably something to do with daylight savings time and GMT -5 being shifted an hour, though that's just a guess.

    I am using Safari as my browser, not sure if that's the issue since I get the same problem in FireFox.

    I'm going to keep looking into this until somebody else can post why the time is off.

  11. @ryan

    looks like there is localization code at the bottom of the js that I missed. For some reason it isn't working though.

    My last post was at 9:55 pm local time (EDT, GMT -5, Toronto) but the script displays the time as 1:55 am (the next day). It's off by 4 hours (not 5, probably due to DST?).

    So it looks like the localization bit isn't working for me in Safari or FireFox. I'll keep digging but maybe somebody with a bit more javascript knowledge can help out? I'm a programmer, so picking apart the code isn't bad, but I don't do much web development so it's all new to me and will take some time.

  12. I took a closer look, and I was kind of wrong, but on the right track. What relative time is doing is calling a function to give you the nice "less than 5 seconds ago", "half a minute ago", "1 hour ago" messages.

    These work perfectly fine.

    The problem comes from when enough time has passed that the function simply returns the date. The date is just formatted and returned and not compared to the variable in the function which takes care of localization of the time zone. Shouldn't be a difficult fix. Basically, whenever you see

    formatTime(date);
    or
    formatDate(date);

    you should be be changing date to the local time zone before passing it to the function. That is, right before you call either of the above functions (which are located in the last two cases of the if statement), do the following:

    date.setMinutes(date.getMinutes() - relative_to.getTimezoneOffset());

    Yay, I now have the correct time displaying. But something else is now broken!

    My last post was 2 days ago at 9:55pm but the script says "Posted 9:55pm yesterday".

    But why? Because the script is kind of making some assumptions that just aren't true. The script will display "Posted ___ hours ago" if the post was less that 24 hours ago. Makes sense.

    The script then makes the assumption that if the post was created less than 48 hours ago, that it should be outputting "posted ______ yesterday" which is only true if posted it at midnight, otherwise the later you posted your tweet, the longer it will display the "yesterday". In my case, 9:55pm is fairly late, so I am getting this "yesterday" well into 2 days after the fact.

    Anyways, The problem is the fact the last if statement uses a constant int for comparison and not a variable time. Here is the solution:

    replace
    if (delta < (48*60*60)) {

    with
    if (relative_to.getDate() - date.getDate() < 1) {

    Which will check if you posted the day before today, aka yesterday.

    Hopefully this will find it's way into the next update?

  13. For some reason this script is now causing a popup window that says:

    "The server http://www.twitter.com at Twitter API requires a username and password."

    Where did that come from?

  14. After some searching I discovered the problem. I am using this script to list updates for multiple twitter accounts. One of those accounts recently set their twitter updates to "protected"

    After removing that particular user the problem went away. And as soon as I can get him to revert back to "unprotected" we should be good to go.

  15. how do you change the color of the font to white? because i need to put it on a black background and the fonts black...you get what i mean :)

  16. awesome! works perfectly and highly customizable. Thanks man!

  17. Thanks for updating the twitter.js with #tag-links - It's working great!

  18. thanks so much for your help. i was searching alot, how to add twitter on my web site but now i get help with your article. now i m adding twitter in my web site. thanks again

  19. Just wanted to say thanks for this, Dreamhost suddenly started blocking php file_get_contents() and your script is a life-saver. Much appreciated!

  20. Is there any way to get the last to be appended with a class such as "last"? On my site, I use this jQuery function to add the class "last" to each final .


    jQuery( document ).ready( function ( $ ) {
    // Add first and last menu item classes
    $('ul li:last-child').addClass( 'last' );
    });

    It is not applying it to the div for my tweets, probably because it's dynamically loading it later. Thanks.

Leave a Reply
Not required

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