Please consider donating: a local project in memory of my daughter

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

Hotlink from Google

<script src="http://twitterjs.googlecode.com/svn/trunk/src/twitter.min.js"></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". This can also be a list (in the format of user/list-name, ie. rem/conferences) or a hash tag.
  • 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_str%/">%time%</a>'
});

Template variables

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

  • text - the actual status message
  • id_str - id of status message (note that id was used before, but for the ids to be correct, you need to use id_str)
  • source
  • time - relative 'friendly' time
  • created_at - raw time
  • user_name - real name
  • user_screen_name - username
  • user_id_str
  • 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 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_str%/">%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.

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

  1. This is really a great script, especially the spinner while content loads in the background! That is a function that I would desperately like to add to this multitweet script, which allows multiple scripts to be strung together chronologically. That multitweet script works brilliantly, but for the all-to-common Twitter delays that greatly delays the rest of the page-load. I wonder if anyone would be kind enough to show how to adapt the spinner/background-load portion of remy's script with the multitweet script? Thanks.

  2. I can't get this to load anything.. I'm an above average programmer and followed the directions to a 't' but my tweets never show up at http://www.freediskspace.com.. can anyone help??

  3. ...I put the second bit of code into a separate js file, which has seemed the solve the problem. Thanks, great code!

  4. Hi Remy. really love this script you have written, though I am having one issue, and it only appears in Opera.

    9:27 PM 22 Mayth - this is the date format I am seeing, but only in Opera, it would appear to be fine in Ffox, Safari, IE and Chrome however. Is this a known issue, or do you know a work around to solve it?

    Many thanks! Jonny

  5. This is great! Is there any way to send the links to a new page? Thanks!

  6. Two questions
    1. How do I get the date/time to display in a different format?
    2. How do I get it to stop trying to load after a certain time.. though it does load lastit does hang up other javascript from displaying properly..basically i just need an ontimeout function that does nothing?

  7. it only hangs part of the page for a few seconds and only in FF and Safari, not in IE
    here is a page example.. the tabs will not display until twitter is loaded... again this does not hang up in IE
    http://www.levelninesports.com/head-xenon-skis-156cm-p-5072.html

  8. handy code! I placed it on a blog. What the heck did I do to get the post time all messed up? If I tweet at 7:15 pm (and the time shows correctly on Twitter) why does my blog display my post as 2:15 am? Is there a setting in this code that I've overlooked? My blog uses wordpress if that makes any difference.

  9. hi,

    Very nice js, thank you.
    But I have a problem with IE8 (always IE...) :
    The tweets are loading fine, but when I try to display the page with their new "compatibility display" thing, tweets are not loading anymore.

    I don't understand where it does come from, I think I have put the code right... but on your page tweets are always loading fine with IE8, with or with "compatibility display" enabled, could you check this please ?

    Thanks.
    (sorry my english is not very good :/ )

  10. Is there a way to call another JS method once the twitter feed displays? I am using twitter js with CurvyCorners and the dynamic HTML breaks in IE7/8. I need to call a redraw method on curvy corners but I do not know when the tweets load at the moment.

  11. Botch the Crab June 2nd, 2009 at 2:47 am

    One more person here to say your script is awesome!!

  12. Wow g8, I was finding this script for my site. Thanks for sharing ur knowledge :)

  13. WORKS LIKE A CHARM! THANKS REM! you are an internet artist!

  14. I've done hours of research, this is probably the best twitter feed code out there. I have one question for you.. I want to display a feed from Twitter rather than an id from a specific account.

    For example Twitter search's feed of 'cnn': http://search.twitter.com/search.atom?q=cnn Is there a way to tell this script to pull up this feed rather than a users feed?

    Thank you

  15. great script perfect for what i needed can i use this script in commercial projects ?

  16. Hey Remy,

    So i am using this code to add twiiter feed to my home page- I would like to add multiple people in one container or "box"
    Please advice

    thanks
    nuidee

  17. Hi Remy,
    Thanks very much Remy. I am going to add twitter into this blog: http://www.everlastgenerators.com/welding-equipments/blog.php

  18. Is there a way to not have bullets next to each twitter update? I'm baffled. I've sifted through the code for well over an hour to no avail haha.

    Any help would be greatly appreciated.

  19. Thanks for a great script!!! However I wonder if there's an easy way to get access to password protected tweets too? Maybe a workaround? Thanks!

  20. Very useful piece of javascript code!
    And as you have also developed the Dotclear plugin to go with, I really had nothing else to do to use it.

    Not being fluent in javascript, I was wondering if there would a simple way to get only the 'fav' tweets for a user. The reason for this is the following : we wanted to give visibility to people who tweet about us by displaying their tweets only. We add them to our tweeter account's favourites on the go.
    And we think it's a good way to help our 'passing by' readers connect to others who share a strong enough interest in what we do to RT us.

    Anyway, thanks for this great tool. :)

  21. Is there a way to implement this on facebook fbml boxes? Standard twitterbadges are not working

  22. Loving this script, especially how easily it can be styled via css.

  23. Remy - your script is perfect - but I cannot get it to work within Typepad - loaded the container script - 100% AOK - but when I copy and post the JS script from your webpage - it totally disappears - when I download the entire script (1.2.2) and then copy and post - it is remaining as text - all this while following the instructions from Typepad -

    Script can be added to a Post or Page using the HTML editor. Click the
    HTML tab on the Compose page and paste in the code. You will not be
    able to use the Rich Text editor when adding complex script to your
    post or page.

    Can you assist - thanks -

    Buff

  24. I set enableLinks:false, but i still keep getting functioning links in the output. is there a way to disable them, or make them open in a new window? thanks

  25. This is Great!
    Is there a way to have only tweets with a particular #tag load? For example, yammer only reads tweets with #yam and it's very convenient.

  26. Remy -

    Forget the first message - june 26 - 12:45 - got the whole script working - very slick -

    I do have a problem - using Typepad - the objective is to have feed to individual posts - i.e. - post #1 gets the feed of tweet t#1 - post 2 gets the feed of tweet #2 - etc -

    What is happening is that when the posts are viewed as stand alones - i.e - with their permalink address - one post per page - the script is perfect -

    However - when the main page of the blog is pulled up - shows post #1 - #2 - #3 etc - all the feeds show up in the newest post - i.e. - post #1 shows the feeds for #1 - #2 - and - #3 -

    The folks at typepad are stumped - as am I - their suggestion - which I already tried - was to load multiple scripts into the file manager - i.e - 1.2.2 & 1.2.2a & 1.2.2b - giving each post its own script to pull from - that did not work - the consolidation in one post - with nothing showing in the #2 or #3 posts continued -

    Is this a limit of your software - am I doing something wrong - is there a workaround -

    Thanks

    Buff

  27. Thanks, this worked charmingly, I was using the statuses/user_timeline API, but did not want my direct messages displayed, and the statuses/public_timeline method always returned 20 updates, so was not really suitable for me to use on my site...

    Thanks,

    Max

  28. ¡Excelente articulo!, gracias :)

  29. Having a problem when trying to use jquery on the same page. The jquery will not execute until the twitter script is finished, leaving a nasty delay. I guess the browser has to parse your script first. Any way to combat this?

  30. Thanks, Remy your code really helped. I was able to fix an issue on my site when using the Twitter Badge. I'm just starting out myself and was able to figure out your example code to get it too work on my own site. Gave you a mention in my latest post so I'm sure my readership of 1 will flood to your site :-)

    Thanks Again,
    Liam

  31. 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).

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

  33. 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?

  34. 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

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

  36. very usefull, thank you!

    -Politiet i Danmark

  37. 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.

  38. 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 ?

  39. @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.

  40. 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.

  41. @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.

  42. 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?

  43. 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?

  44. 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.

  45. 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 :)

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

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

  48. 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

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

  50. 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