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.

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

  1. I’ve seen several questions/requests in the comments (one of them mine!) concerning support for multiple Twitter feeds (so that they’re woven together into one timeline). Perhaps you can clarify whether that is possible. I know Tweetblender will do this, but I much prefer your script.

    Thanks again for a wonderful script!

  2. Hate to be a pest — just wanted to bump this a final time…. Thanks!

  3. Just wanted to say thanks Remy – this is exactly what I was looking for. Something small, fast and easy to style. Perfect. Good work!

  4. ugh. I feel so dumb, I just know I’m missing something here. I’ve added the script and container HTML, downloaded the most recent .js files…but I CAN NOT get this to work at all, regardless of linking to google’s .js or mine. The only hint I’ve found is the following error on my live webpage:

    Message: Expected ‘;’
    Line: 1
    Char: 10
    Code: 0
    URI: http://www.twitter.com/statuses/user_timeline/RoswellJudoClub.json?callback=twitterCallback1&count=20&cb=0.9483407327380756

  5. I also just want to say this is *Exactly* what I was looking for – small, fast and easy. Good work! Thank you for the time you saved me!

  6. Thanks for this script – I’m a designer who is expected to develop. Really appreciate simple scripts with clear explanations on implementation and even better CSS classes!

  7. I’m developing this website for a client, and this tutorial really saved me hours of figuring out how to insert his Twitter stream into a static HTML.

    Thank you for your very detailed and simple to follow tutorial!

  8. How do I make it show retweets made by that user?
    Except that, this is a great script! Thank you!

  9. HI, I’ve added the code, only when I load the page I get the Twitter preloader, but after it disappears it is not replaced with my Tweets in Firefox 3.6.8

    My pages are PHP. Is that the problem?

    Jim

  10. remy – i just wanted to say thanks – works great

  11. one more thing – I want to send my condolences – I have 2 daughters and I can’t imagine the pain you are feeling

  12. A couple of people had mentioned the bullet point that is showing up when using this — they said they fixed it without giving any explanation how…

    Couple someone please explain how to get rid of the Bullet Point that shows up in front of my tweet when using this script?

  13. Two things, one important, one not.

    Important: so sorry for your loss. There are no words, and all this pales in comparison.

    Less important: for folks banging your head against tweets not showing in IE, what template are you passing? I originally was passing

    <li>%text%</li>

    but IE errors when the li is passed in. It accepts a, img, and span just fine. But not li. So I redid it so that no li was passed in, and IE is now happy. Or, as happy as it ever gets.

  14. Remy,

    just wanted to say thanks for this. Saved me a lot of time.

    Just one quick questions, is there any way to make it user #tags rather than a user id?

    Seb

  15. HI, I’ve added the code, only when I load the page I get the Twitter preloader, but after it disappears it is not replaced with my Tweets in Firefox 3.6.8

  16. Thanks for posting this and also thanks for posting the hot link source code, very helpful! Thanks :-)

  17. Wow, really nice. It is working fine. One question tho:

    Besides my twitter stream I also want multiple searches for “#keyword” to get displayed. I like the code something to be like this for the searches.

    * search for #keyword1(some script only to point out what to search for, butt still using the basic code you provided)
    * search for #keyword2
    * search for #keyword3

    Hope someone understands what i’m trying to do. Willing to buy you some coffee for solution :)

  18. Thanks for the post. I’ve been trying to figure out how to properly add twitter to my blog and this post has been great help.

    Cheers!

  19. Hey! The script works fine and i am very pleased with it, it’s great!

    I don’t know if it is because i have my time-zone set in twitter settings but i get a 3h difference from my actuel tweet-time. I have converted the script to 24h time, but the problem accurs with the original script too.

    Solution?

    THX!

  20. Hampus , You are right that really works if you follow those steps the intergration will be right.

  21. Great – fantastic, super fantastic. I found you off this – http://think2loud.com/adding-twitter-to-your-website-with-javascript/

  22. Hm, is there any way to include retweets?

  23. Hi, I am also trying to get re tweets to show up, is there a solution for this yet?

    ps thanks for the script, it works great otherwise.

  24. Retweets seem a necessary addition. Please, update your script to display them.

  25. Great script, but we too, like many others here, are asking a question that no one has answered yet (looked through all 22 pages of comments!) how to enable RETWEETS (RE-TWEETS) to show up? Seems that’s not possible as yet? Will it be? Hopefully any reply could also go to our email as we’d be unable to monitor this forum, thank you.

  26. Hi there, I am exploring all this in order to have it included in my new website. Point is: I have to fill out my Twitter-password every time the page is loading.. It seems to me that having it included in the html-code might be a possibility?? Does anybody has a solution on this?

  27. Hi everyone,

    How do you get rid of the bullet points from the feed as it is mucking up the alignment of the twitter feed?

    Thanks

  28. Is there currently any way to concatenate each tweet? If not, are you considering adding the ability to do so in future updates?

    For example, for design reasons, I would like to show only the first 35 characters of each tweet, followed by three trailing dots (…).

  29. Is there any way you can add something to the UL tag in the HTML that gets printed by the script?

    For example: ul data-role=”listview” data-inset=”true”

    ?

  30. Add this to your css to get rid of bullets:
    #tweet ul {list-style-type:none;}

  31. hello, anyone knows how to make it automatic updates of tweets? without having to refresh the site?

    Thanks!

  32. Hey guys, any idea on the Retweets yet? I’d love to get those also showing.

  33. Any change for 24hour clock and without the ‘AM’ & ‘PM’ in Europe we don’t use those :). As I really don’t know how to change the code regarding the time-functionalities. Please help.

  34. After performing a search for the twitter style widget, and here i got one cool widget too…
    awesome, thanks^^
    Into the lists on my posts ;)

  35. Is it possible to add the “retweet” and “reply” buttons?
    If so how do you do it?

  36. Your code pulls my twitts in the browser fine, but when I go to view the source code that my browser rendered, I can not find the html code for my twitts.

    All I see is this below. How do I get your script to write the twitts in my code?

    I want to make sure when the search engines visit my site that they too can read my twitts in the source code.

  37. on my page everything goes well, but w3c don’t validate de linlk document type does not allow element "a" here

    …template: '"%text%" %time%'
    Anyone can help me!!
    thanx

  38. I’ve implemented the script on a website of one of my customers. I’m using a link (in the template) to Twitter with the following code: http://twitter.com/%user_screen_name%/statuses/%id%. Unfortunately, sometimes the link does’nt work and the following text is shown on Twitter: “Sorry, that page doesn’t exist!”. It seems something goes wrong with the ID, because the real ID is (sometimes) some numbers higher than the one that is shown. How can I fix this?

  39. @LaatR – change %id% to %id_str% – I just remembered that Twitter updated their API, so I’ve updated this post to reflect the change too.

  40. Grazie mille, works fine now!

  41. Hey Remy, is there any known issue when using Cufon to style the Twitter text?? Would you mind taking a look at a website I’m coding? Somehow can’t style the plugin generated text with Cufon, thought it was ’cause of the double quotes in some words, should I escape some code to generate plain text?? https://github.com/tatygrassini/Brilliante_Layout

  42. How could i style the time for tweet? also i want to get rid the “about” minute ago something. Is there any way to do that?

  43. Hey Remy, thanks so much for the twitter.js script. It’s one of the simplest and easiest to use I’ve seen. Anyway, I’m having trouble with the time stamp parsing. For some reason, a time that should read “5:40 AM Jan 28th” is coming out as “0 / 28 1:40 pm”

    My template code is:

    template: '%text% <a href="http://twitter.com/%user_screen_name%/status/%id_str%/">%time%</a>'

    I tested it with a different twitter account, and that one works fine. Any idea what’s going on?

  44. Great plugin, been using it for a while now. But it seems it has some errors, or so says JSLint on jsfiddle :) Maybe you could resolve those errors because if I minify it along with other scripts, it kinda kills all of them :)

  45. Any way to get this script to generate the html such that each list item had a different class? ie. , tweet 2, tweet 3, etc. This would be useful because I’d like to make each tweet a slightly lighter color, as if it were fading off as the tweet got older. Can anyone advise on this? Feel free to shoot me an email at kevindosi at gmail dot com.

  46. Dear Remy: I am using this script, but it put a lot of empty space up and down of the twit. How I can clean that empty spaces ? I tried with CSS and don’t work. Thanks !!

  47. Wonderful script! I need to give the unordered list tag an ID. I found the spot in twitter.js to do it, and I can manage to shove stuff inside the ul tag. (line 104) My problem is I’m not good enough to get it to look like <ul id="ticker01">. Can someone give me a hand? Thanks!

  48. Great Work! Just a quick question…

    Is it possible to output a particular list on my twitter account to my website instead of my ID?

  49. Great script, I am going to use it for a Salsa dansschool website I am building right now for my dans teacher. Works really fine in the test fase. How do you show ALL the REPLIES on tweets in the page? I think that could be rather important for making appointments, changing schedule, cancelling lessons etc.

  50. Remy, for a future release, can you please add an option where we can disable the ul li tags for the output? I have issues trying to remove them