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 a fantastically easy-to-use piece of webdev. Thank you very much!

  2. Remy, amazing job, I knew nothing about Twitter and was helping a friend broadcast it on her website. Had it up and running withing minutes. Love the way it is called so effortlessly. Thanks!

  3. Awesome script, works perfect for me, but I have one question. I am showing the most recent tweet in a larger font and I have older tweets below it. So the layout I want to use is one tweet then 5 tweets underneath. The script pulls everything fine, but on the list of 5 I want to pull 5 after the most recent. I'm not sure how to edit the js file to fix this. I was also thinking of pulling in 6 and using css to format the top one. Any tips on how this can be done?

  4. Hey Remy, Nice script! I got a question ,. how can i have several tweets in the timeline? Is it possible with your script?

  5. ORSUM - simply ORSUM

    Took the code as it is and integrated it into people's profiles on my website - like this - http://www.runsaturday.com/Profile/TabId/82/UserId/3/Default.aspx

    Then took the code and extended it to allow a search term to be used (I suspect there were other ways of doing this but I wanted to play!) - http://www.runsaturday.com/Talk/Twittering/tabid/108/Default.aspx

    Have had some problems running it under Opera (eeek - opera) and some problems with the timezone returned from searches - but overall simply ORSUM :)

    Next time I'm in Brighton I shall buy you a beer (and chips)

    Here's an attempt at my code...

    
        window.getSearchTwitters = function(target, id, count, options) {
            guid  ;
    
            if (typeof id == 'object') {
                options = id;
                id = options.id;
                count = options.count;
            }
    
            // defaulting options
            if (!count) count = 1;
    
            if (options) {
                options.count = count;
            } else {
                options = {};
            }
    
            if (!options.timeout && typeof options.onTimeout == 'function') {
                options.timeout = 10;
            }
    
            if (typeof options.clearContents == 'undefined') {
                options.clearContents = true;
            }
    
            // Hack to disable withFriends, twitter changed their API so this requires auth
            // http://getsatisfaction.com/twitter/topics/friends_timeline_api_call_suddenly_requires_auth
            if (options.withFriends) options.withFriends = false;
    
            // need to make these global since we can't pass in to the twitter callback
            options['twitterTarget'] = target;
    
            // default enable links
            if (typeof options.enableLinks == 'undefined') options.enableLinks = true;
    
            // this looks scary, but it actually allows us to have more than one twitter
            // status on the page, which in the case of my example blog - I do!
            window['twitterCallback'   guid] = function(obj) {
                if (options.timeout) {
                    clearTimeout(window['twitterTimeout'   guid]);
                }
                renderTwitters(obj.results, options);
            };
    
            // check out the mad currying!
            ready((function(options, guid) {
                return function() {
                    // if the element isn't on the DOM, don't bother
                    if (!document.getElementById(options.twitterTarget)) {
                        return;
                    }
    
                    var url = 'http://search.twitter.com/search.json?callback=twitterCallback'   guid   '&count=20&q='   id;
    
                    if (options.timeout) {
                        window['twitterTimeout'   guid] = setTimeout(function() {
                            // cancel callback
                            if (options.onTimeoutCancel) window['twitterCallback'   guid] = function() { };
                            options.onTimeout.call(document.getElementById(options.twitterTarget));
                        }, options.timeout * 1000);
                    }
    
                    var script = document.createElement('script');
                    script.setAttribute('src', url);
                    document.getElementsByTagName('head')[0].appendChild(script);
                };
            })(options, guid));
        };
    

    - but postable removed all the + characters!

  6. We too are having the problem... Please wait while my tweets load

    If you can't wait - check out what I've been twittering

    Please help- any ideas!? Thanks.

  7. Got a problem :(

    I've implemented it, perfectly, everything works fine in Firefox, but not in Safari! It works if i empty my cache through Safari, then refresh. If i just click refresh without clearing anything, it doesn't show! I'm using the latest Safari 4 Beta, so i guess this is just a bug, but i was wondering if you have any tips? I've tried attaching some metadata cache scripts, but nothing seems to work.

    Thanks!

  8. Hi, Rem,

    Thanks for the plug in!

    I installed it on my personal website and it was working for for days, but today I noticed a change: it seems like any new tweets show only the first time I load my page. If I reload, the tweet disappears, and it just shows blank. What could be going on? I don't think I changed anything.

    Thanks!

  9. Nevermind, I figured it out. It seems to be a problem with Safari 4. Go figure.

  10. Thanks a lot, Remy. This is far superior to the script twitter makes available.

  11. When I use this in Safari 4 (mac), it loads fine the first time, but if I refresh the page, it'll clear the "Loading…" text but fails to actually load my tweets. But If I empty the cache, it'll load it the tweets again.

    I tried changing "getTwitters('tweet', { " to "postTwitters('tweet', { " but this won't load the tweets at all.

    Is there a fix for this? I love the script, but its a bummer it'll work in every browser but Safari 4.

  12. Script works for the most part pretty great... though the new version seems to not pull anything up in Safari 4, and version 1.11.2 does pull the tweets up, but it keeps the loading text at the bottom. any ideas? thanks!

  13. Hi, my doudt is how i can do for the post have one limited number of characters, its possible? In PHP language i can read the string, but in this case I cant read the variable %text%. Somebody can help me?

  14. Hi Remy

    I just pulled the widget from Twitter.. and it seems to work for what I want - except the space around the div area

    ..will using your set-up give me more control over the display?

    See here at the foot of my home page:

    http://www.ezs3.com/public/main.cfm

    TomC

  15. I have been playing with your script and the twitter widget script. I have been able to add in the usernames and icons. But it looks like i am unable to add friends statuses. Though in the twitter widget you can just change user_status to friends_status and i can get the updates. Unfortunately i don't know how to add in their usernames or icons. I have downloaded the blogger.js file, but i am not sure what i need to alter.
    Any help would be appreciated. Thanks. you can dm on twitter @aaronjbates

  16. Will this work for displaying the tweets of multiple Twitter users, e.g. for a family:

    Dad
    tweets

    Mum
    tweets

    etc.

  17. Great script ... just what I needed. It also works well embedded in a gadget for iGoogle. Tried to use Twitter's scripts at first, but couldn't figure out the css to change the Time formatting. Your script made it easy, though.

  18. I've copied the templates as you have them, but I can't get more than one tweet to display correctly. 1 twitter is fine, but if I set the count to 2 or more, they try to display on top of each other. It appears that it isn't creating new list tiem () on my site.

    Anybody have any ideas as to why?

  19. Wow, that's great code, thanks!
    Now go teach Twitter how to do their jobs properly :)

  20. thanks for this great app for my website, though i have some problems with opening the (xxx days ago) link, it opens in my iframe.. I've set _blank , but doenst work.. please help?

  21. I think there is an error in your css file. The last piece should read:
    #twitters SPAN.status {
    font-style: italic;
    }

    Also, I made two changes in order to get tag queries to work. One triggers a tag query using '#' in the id, e.g. '#sxsw'. One change is in the line before the "renderTwitters" call:
    if ("results" in obj) {obj = obj.results;} //BP
    renderTwitters(obj, options);
    and a 3 line replacement for the url assignment:
    var url;
    if ('#' === id[0]) {url = 'http://search.twitter.com/search.json?q=%23' + id.substring(1,id.length) + '&callback=twitterCallback' + guid + '&count=20';}
    else {url = 'http://www.twitter.com/statuses/' + (options.withFriends ? 'friends_timeline' : 'user_timeline') + '/' + id + '.json?callback=twitterCallback' + guid + '&count=20&cb=' + Math.random();}
    Here's the template I used:
    template: ' %from_user% said: "%text%" %created_at%'
    This seems to work for IE and Firefox on Windows and Firefox on Mac, but not Safari. Any ideas on how to make it work for Safari would be appreciated.

  22. Its working...Thanks Remi......

  23. Hi.

    I have the same problem as Justin. I'm using this implementation inside an iframe and need the links to open in a new window. Any ideas how to make that happen?

    Any clues are really, really appreciated.

    thanks in advance,

    Keith.

  24. I'm trying to change the date format to:

    20 March 2009

    I've gotten this far...
    20 Mar

    but i dont know where or what to change to make the month the full text and put in the year also

    thanks, great great script!
    -Statice

  25. [...] 1.  Download twitter.js from Google 2.  To install the code so that it doesn’t “hang”, follow Remy Sharp’s excellent step by step guide [...]

  26. [...] Option 2 - The Unofficial Way: 1. Download twitter.js from Google 2. To install the code so that it doesn’t “hang”, follow Remy Sharp’s excellent step by step guide [...]

  27. Hi Rema. love your work. got it going to follow my mate lance armstrong on my site. Do you have any view on how I might combine multiple tweets from different people into one list in time order? thanks

  28. Does anyone have any problems with the script and IE6 or IE7. It seems to not work for me. It does perfectly for other browsers. Not sure if its the script of other scripts on my site. thanks

  29. micah Honeycutt March 26th, 2009 at 9:10 pm

    I love the tool, but my %text% just runs off the page and doesn't line-break. any idea why?

    http://tinyurl.com/c6qxbv

  30. This seems like a great and popular solution - just seeing how long this thread has been opened and how many people have commented. My question (and maybe I am missing something obvious): is this solution superior to the embed solutions that Twitter provides (Flash and JS/HTML)? Or was it developed before that was available from Twitter?

  31. I'm looking for a way to display a set of specific tweets in a blog post. ie. A user tweeted during a presentation and I want it to always display those specific tweets. Is it possible to get the script to display specific tweets with their status id instead of having it load the latest tweets?

  32. Whew, you sure have a lot of comments on this page. Just wanted to add one (sorry, heh) and say this is a great script, and I was able to implement it flawlessly into my personal blog. Thanks!

  33. I get a problem in IE7/6 too. I downloaded the latest version but nothing loads at all. Every other browser works fine - Chrome, Opera, Firefox, Safari.

    Strangest part is, it works fine in IE7 when i come to this site. What could be the issue there?

  34. Sorry, but I am a little confused, perhaps it's just because it is late. But never-the-less I can't seem to make this work. Here is what I did...

    I've uploaded the Twitter.js file to my server. I've added the following script to my header:

    getTwitters('tweet', {
    id: 'rem',
    count: 1,
    enableLinks: true,
    ignoreReplies: true,
    clearContents: true,
    template: '"%text%" %time%'
    });
    (I have changed the user screen name to match mine).

    I've added the following to my sidebar:

    Please wait while my tweets load
    If you can't wait - check out what I've been twittering

    But what I am confused about is what is the code that goes in the sidebar that calls the script into the sidebar.

  35. The user_profile_image_url for avatar has been updated to profile_image_url in remy's latest JS release.

    I thought it'd be best to post it here since the post itself wasn't updated and I was wondering why my avatar wasn't loading at first.

  36. My bad. It's still the same. But I couldn't find the documentation the %user_profile_image_url% is wrapped in IMG tags. :)

  37. Ahhhh this is perfect. Removing those @ replies is essential! Excellent, so glad I found this page.

  38. This is PERFECT, I had been hunting for AGES to find away to get rid of the @replies.

    How do I get rid of the bullet point... in the Java Script? In the div? in the script? HELP!

  39. is there a way to provide a message if the username is bad or have been deactivated?

  40. Hi micah Honeycutt, do you manage to solve the text run off the page issues.

    Just remove the line white-space: nowrap; at the twitter.css will solve it.

    .twitters ul {
    list-style: none;
    padding: 0;
    white-space: nowrap; (remove this line)
    }

    Hope this will help.

  41. I don't understand this. How do I add this to a Blogger blog?

    Could you spell it out to me as though I'm a two year old? Because I think this should be easier.

    Thank you,

    Gambit

  42. Is there any way to force the feed to reload?

    I'm using ajax tabs, and though the twitter feed works when the site is loaded, when a user navigates away and then back to the twitter feed, it won't reload.

    Here's the site so far: mrfalconmusic.com/remysharp
    The feed loads at first, but if you click on another tab, then back, it won't.

    Warning: watch your step.

  43. Cool! Thanks! How does a site like http://www.twixdagen.se work? It got several twitter feeds into one feed.

  44. I cannot get rid of that dang bullet. Im not sure if im not sure whats wrong. i know i add twitter_update_list li {
    list-style-type: none;
    } but then what?

  45. I dont know what i was thinking yesterday. I wasnt paying attention at all. /facepalm

  46. Hi
    Thanks for the code. It all works for me except that I can't get replies to show. I have the ignoreReplies: false flag set. I'm new to Twitter so I'm assuming a reply is when I send a Tweet to @username
    Any thoughts appreciated
    Thanks
    Tim

  47. nice work...but it broke every single javascript link on my ASP.NET 2.0 page.

    also, I had to use


    getTwitters(
    'twitter_update_list',
    'tylerazevedo',
    1,
    { enableLinks: true,
    ignoreReplies: true,
    clearContents: true,
    template: '%text% %time%' }
    );

    to get it to work...notice i moved the { over 2 or 3 parameters.

    I assumed this was because in the file (1.12.2) I downloaded you only defined the params I enclosed in brackets as optional.

    This is the only javascript I have on the page since I'm more of a server side developer....the error I am getting on any browser when the page loads says that whatever element is referenced in the javascript immediately after my reference to your file is null. So if it is in the head, it says 'theForm' is null. If I put it before a content place holder it says 'theContentPlaceHolder' is null.

    This is only if I reference it as a file. If I put the javascript directly on the page it works fine. But I'd rather not bloat my master page :)

    I fixed it by creating a new script block and declare a worthless variable immediately after the script block used to reference your file. It works, just kinda funny that I have to do that.

  48. Great script! Any chance of this API being updated to support blasting out tweets from an account rather than just pulling down the feed?

  49. Great script - thank you! Quick query for you please - I have incorporated your script into my signature on my forum. However, if I have multiple posts in a thread on any given page, the tweets only appear in the first instance and not for the remaining posts containing my signature on that page. So basically, how do I get the script to fill in all the <div id="tweet"> boxes and not just the first one? Thanks

  50. @10drill: Thank you! Just what I needed.

Leave a Reply
Not required

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