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. can someone help out a brand newbie. i have some basic css and html knowledge, but seriously lacking on the javascript.
    can someone just correct me where i dont understand.

    currently ive basicly just added the javascript code from twitter.com to my index file and it seem to be getting the updates. to use this method, it sounds that i must first copy this twitter.js file to the same folder where my index is. then copy the code...

    getTwitters('tweet', { id: 'rem', count: 1, enableLinks: true, ignoreReplies: true, clearContents: true, template: '"%text%" <a href="http://twitter.com/%user_screen_name%/statuses/%id%/" rel="nofollow">%time%</a>'});

    in either my head tage or at the end of the body? am i right so far?
    and if so, do i still leave the javascript that i originally got from twitter.com as i have it. or is this script completely replacing it?

    and in the above code, what all do i need to update with my info?
    i see a place where it has id: 'remi' so im guessing that i need to replace that with my twitter name or number. is there any other entries in this java script that i need to replace with my own.

    is there any thing in that twitter.js file i need to replace?
    currently im just trying to get basic functionality and know that it is working. ultimately all i want is something indicating that its loading if twitter is acting up, and to display an indication that twitter is down if for some reason twitter dont load.

  2. hello everyone,

    ok i figured out the answer to the above question that i posted about how to set everything up.
    the next question that i have is that, after attempting to load the twitters with the progress gif going, if for some reason the twitters dont load after about 10secs, i want the loading gif to disapear and to have a message pop up saying that "something is wront with twitter..."
    sorry for the inexperience, in the mean time ill fish through these 150 post for an answer.

    can you also tell me how to test the above, for example can i create an error in the code and have it try to load twitter, then after 10sec bring up the message?
    please help..

  3. Well, I was really excited about this. However, it doesn't work on Firefox. :(

  4. Nevermind. It works intermittently in either browser for me. Seems like an error on my part.

  5. Hey, so I feel pretty dumb for even asking... but is this code possible to use with a Tumblr blog? If so, how? As you can tell, noob only begins to describe me.

  6. Twitter Code Enhancement...?

    Remy, fantastic code! I really appreciate the great code you've provided here!

    I recently decided to implement Twitter on to one of our blogs for my wife and I. In doing so, we found this great script over at AfterGlide that allowed us to deliver both of our tweets in one single timeline: http://www.aftergeek.com/2008/02/combine-multiple-twitter-feeds-on.html

    However, as you're obviously aware, Twitter has a habit of going down or going pretty slow at times. This in turn causes my website to stop loading for the user as their browser waits for Twitter to respond.

    I searched around and found your additional amazing script that works through that loading issue.

    So now I have two scripts with equally desired functionality (multiple user tweets in order of 'tweet' time + faster page loads with a pleasant 'please wait while my tweets load' message) but very little knowledge on how to incorporate them together. If I could somehow understand how to take your code and insert it into Jeremy's, or vice versa, I think we'd have a perfect winner here.

    Is this something you might be interested in looking into? I'm going to query Jeremy, the author of this other code, with the same request. If neither of you are interested in combining your two code bases, then I'll guess I'm stuck trying to learn it myself. But I figured I try the path of least resistance first - LOL!

    If nothing else, thanks for listening and thanks for the great code to begin with!
    - Bruce

  7. I've looked into the Opera problem a little: it seems as if the Twitter callback doesn't provide any data after refreshing the page (i.e. the obj array is empty). The Twitter REST API documentation doesn't mention anything about the callback parameter, but I managed to stumble across this:

    http://www.wait-till-i.com/2008/04/11/opera-rest-apis-module-patterns-and-generated-script-nodes

    although there are no sightings of that particular error message.

    Not being the JavaScript guru I wish to become, I'm trying to wrap my head around the "mad currying" parts of the code ;)

    @Remy: thanks for this great piece of script!

    Cheers,
    Martin

  8. @Martin Häger,
    so how to force Opera to display this script correctly?

  9. Tweets that I delete still show up, until a new tweet is added. Any idea why?

  10. @Bryan - that's really odd. The twitterjs only shows what Twitter sends through - so it sounds like the API is still sending through the deleted items. Perhaps raise it on getsatifaction.com ?

  11. Hi Remy - this is great stuff!
    I just have a quick question - is it possible to have 2 blocks of JS for the same user? I am trying to display the twitters of the same person on 2 different pages of the same site, using different html in the 'template'.
    So far, I have only been able to make it work by using the username in one block of JS, and the numerical ID in the other. Just wandered if there was another way to do this?
    Any advise would be much appreciated! Cheers!

  12. Great article. Definately usefull. Thanks a lot to the author.

  13. Worked a treat - thanks for sharing!

  14. @Paul - You Said "
    @Paul - two different ways are available:

    1) split out the string like this:
    (I didn't do this one)

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

    I put it in a separate file called social.js and linked to it.
    but it won't load my tweets, what's going on. Heres the code which is just before the body tag but I have tried it in the head section

    <?php wp_footer(); ?>
    <script src="http://alexrogahn.com/sitewide/js/social.js" type="text/javascript" charset="utf-8"></script>
    <script src="http://alexrogahn.com/sitewide/js/twitter.min.js" type="text/javascript" charset="utf-8"></script></code>

    inside the social file is this

    getTwitters('tweets', {
    id: 'alexrogahn',
    count: 1,
    enableLinks: true,
    ignoreReplies: true,
    clearContents: true,
    template: '%text% <a href="http://twitter.com/%user_screen_name%/statuses/%id%/">%time%</a>'
    });
    // This gets me past validation :) 

    and in my "social sidebar"

    <div id="social">
      <div id="tweets">
        <ul>
          <li>
            <p>Don't mind this, its just Loadin' me Tweets <img src="/wp-includes/images/smilies/Smile.png" alt=":)"/></p>
          <img src="sitewide/images/spinner.gif" class="aligncenter" alt="LOADING"/>
          </li>
        </ul>
      </div>
      <a href="http://twitter.com/alexrogahn"><img src="sitewide/images/follow.png" alt="Follow Me"/></a>
    </div>
  15. Its ok I screwed up some code, my bad >:(

  16. The script doesn't seem to be working today. Perhaps something changed with Twitter?

  17. @Amos - nice spot. Though no - it's not my script. I've just checked the 'net' tab in Firebug and it looks like Twitter's API is throwing an internal server error:

    http://www.twitter.com/statuses/user_timeline/rem.json?callback=twitterCallback1&count=20

    I'm sure they've got their code monkies on it and should fix it soon enough (fingers crossed!)

  18. I notice that in your newest version (1.11.1) you incorrectly use "setTimeout" function because it take millisecond till timeout as a parameter.

    from line 143

    if (!options.timeout && typeof options.onTimeout == 'function') {
      options.timeout = 10;
    }

    and from line 180

      options.onTimeout.call(document.getElementById(options.twitterTarget));
    }, options.timeout);
    

    because you use value of 10 millisecond instead of 10000 millisecond (10 second)

    the code from line 180 should be

      options.onTimeout.call(document.getElementById(options.twitterTarget));
    }, options.timeout*1000);
    

    sorry for my bad english but I hope you'll get the point...

  19. @NuttyKnot (I edit your code down a touch - I hope you don't mind). I don't know how that got in because I remember seeing that before and fixing it, I just have reversed it back in! Thanks for pointing it out - I'll sort it now.

  20. I can see that its working at your page but I have spent the last 90minutes trying to make it working but can't do it. I even tried this on a blank page with nothing else and it didn't even work on that one too.

    I created a file load.html with twitter.js in the same directory. Contents of load.html were:

    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    
    <head>
    <script src="twitter.js" type="text/javascript" charset="utf-8"></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>
    </head>
    
    <body>
    
    <div id="twitters">
    <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>
    
    </body>
    </html>
    

    Even this is not working. Any help would be appreciated!

  21. @Ashfame container div id should be "tweet" (as in the function)

  22. "@Ashfame container div id should be "tweet" (as in the function)"

    Thanks; this was really stumping me.

    Maybe edit the sample code, in the step by step, to have the id read tweet or put twitter in the sample js.

  23. Hi, Remy! First, I want to thank you for writing this code. For those of us who aren't Java developers, it makes life a lot easier.

    I have a very stupid question, though -- I'm adding this to an iWeb page using the iWeb "HTML Snippet" tool. I put together a CSS file with some of the code listed above to get rid of the bullets and format the text. How do I call this from the HTML?

    Thanks in advance for your help.

  24. Ignore my first message (above). I figured out how to call that. However, the "bulletproofing" is not working in my undoubtedly crappy CSS file.

    #tweet {
    	font-family: "Trebuchet MS", Arial, sans-serif;
    	font-size: 9pt;
    	color:#000;
    }
    
    twitter_update_list li {
      list-style-type: none;
    }
    

    Some day I will learn how this all works... Today, I'm trying to get an article written. I'd sure appreciate your help.

    Thanks!

  25. How difficult would it be to define a custom tweet prefix to ignore in the same way @replies are ignored? Example: my new blog posts get tweeted with a prefix of "[confoozled.com]". Having these show up on the blog is kind of redundant. Instead of having to quickly think up something new to say after I post an entry, it would be nice if these just didn't show to begin with.

  26. Looks like Twitter have broken things again. Just since yesterday, I keep getting the spinning wheel when tweets are trying to load ("Please wait while my tweets load")....any ideas as to a work around for this? I see the the same thing happening here, so it's not just at my end.

    Thanks.

  27. why is that the content disappears on page refresh? The first time it shows all the tweets... but when you refresh the page they disappear? It does this locally for me as well as online

  28. OK, all is well again. Twitter had a bug and they just fixed it. You can follow this thread if interested...

    http://getsatisfaction.com/twitter/topics/my_blogs_twitter_feed_wont_remain_keeps_disappearing_help

  29. Hi there. I still can not make it work..Anybody able to tell why? this is the simple page I'm including the script into: http://www.morenafiore.com/new/twitter.html

  30. @morena:
    set id to containing div to "tweet", not "twitters"

  31. Great script; I've used it to replace Twitter's "official" script, so I can exclude replies and change the template. One suggestion, though: In the documentation on this page, you name the container "twitters" in the HTML but refer to it as "tweet" in the JavaScript. Consistency would make this a bit less confusing. Thanks!

  32. @Trevor + everyone else that pointed it out - thanks! I've now sorted out the example so that the ID is consistently referred to using the same name. Sorry for the confusion!

  33. Remy, what about Opera? The alternative script: http://tweet.seaofclouds.com/
    works fine - I mean after refresh tweets don't disapear.

  34. @grotos - basically there's some strange Opera/Twitter thing going on, where the result is coming back empty. I'm certain it's on the server side - because the content changes, but it's to do with Opera too. Just try putting the JSON hit in Opera, then hit it again, it'll come back empty.

    The 'seaofclouds' works because they're hitting the Twitter search API. I've been toying with moving to the search API, particularly as it can also support getting some friend tweets.

    Perhaps it's time to move across to the different API now?

  35. How can I add linebreaks (or {br}) in between the twitter entries? Help please.

  36. @Remy: Thanks for clarifying. for now I'll have to stick to 'seaofclouds' solution.

  37. [...] Twitter Plugin: Add Twitter to your blog step-by-step. [...]

  38. Hi all!

    For me, the script works fine, thks Remy :) but I noticed that wont refresh from some hours ago... That's a problem of Twitter or of my implementation of the script?

    That's my page:

    http://www.ekilater.com/

    Thanks in advance!

    Iván

  39. Ok, no prob.

    I noticed that the thing is the script doesn't load any twitt starting with @..
    That's normal, right?

  40. Thanks! just what i was looking for and really easy to implement!

  41. Hey Remy, just wondering if you fixed the IE bug talked about back in August.
    It looks like the feed on your site now works in IE, but still not working for me, and haven't seen anything in your comments to suggest it's been fixed.

    I downloaded the latest and tested it on my test server, didn't work for me. Maybe I missed something else?

    What's the score?

  42. My website uses Smarty templates and this bit of code:

    getTwitters('tweet', {
      id: 'itmdesign',
      count: 5,
      enableLinks: true,
      ignoreReplies: true,
      clearContents: true,
      template: '"%text%" %time%'
    });

    is causing a syntax error. Any advise?

  43. [...] Add Twitter to your blog (step-by-step) [...]

  44. Thanks so much for this--great script, all the way around. I'm having some inconsistent results with this script in IE only; the feed loads sometimes but not others. When it does not load the "Please Wait...etc" stays up there and will not leave. Any thoughts on what might cause this?
    Thanks,
    Nick

  45. [...] and are tech minded you can even add Twitter to you blog by using this script by Remy Sharp: http://remysharp.com/2007/05/18/add-twitter-to-your-blog-step-by-step/ All the codes and step by step instructions are found at his blog at [...]

  46. Is it possible to only show the message that contains the keyword I want?

    Let's say, I want to show my tweet that only has the work "PHP" and not the other one?

    Thanks for your help.

  47. Hi thanks for the code it's awesome
    but actually I dont want to use tag
    how can I do that?

  48. Works really well thanks.

    Rob

  49. Hi Remy.

    Excellent!

    Just one small point. When twitter returns an error I can see no way way catching it and displaying the error.

    I tried editing your code, but my JS skills are not up to it. I couldn't see why the renderTwitter function didn't run when an error was returned, even though the ready state was fired (I think)!

    Here's a sample error generated by sending a phoney twitter ID:
    twitterCallback1({"request":"\/statuses\/user_timeline\/sdfsdsdfsdf.json?callback=twitterCallback1&count=20","error":"Not found"})

    You also get an error if you exceed 100 requests per hour.

    Just a suggestion for the next release. Sorry I was too useless to do it for you :-(
    Steve

  50. RRR'r Twitter me timbers... Excellent script, I've gotten the bug of late so this will be implemented asap. Thanks very much.

Leave a Reply
Not required

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