• « Pretty in Print: tips for print styles
  • When links in ULs don’t work in IE »
18 May

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

Hotlink from Google

<script src="/img/spacer.gif"> 

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 spacer

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 class="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="/img/spacer.gif"> 

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="/img/spacer.gif"> 

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

You should follow me on Twitter here I'll tweet about JavaScript, HTML 5 and other such gems (amongst usual tweet-splurges)

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

« Previous 1 8 9 10
  1. spacer Faraz March 31st, 2011 at 1:17 am

    Mate, That was Fantastic. Now one question, How do I make it so that it refreshes it self, so I dont have to refresh the whole site, to ge the latest Tweet.

    Thank you.

  2. spacer kjhank March 31st, 2011 at 10:34 am

    Is there any way to use this script without specifying an id of an element? Eg. by inserting it in an nth section/article in the document? I’m trying to create a stylesheet without id-s and classes, and I’m having trouble decyphering your code to use something like document.getElementsByTagName.

  3. spacer ThilliMilli April 4th, 2011 at 4:03 pm

    Great!
    And also easy explantation, even for a noob like me. Works well on my blog.

  4. spacer The_Anarchist April 4th, 2011 at 11:56 pm

    Rem: great twitter code, really nice work. Thank you for your hard work you’ve put into it.

    I like Faraz think it would be a nice option to have some type of ‘time to refresh function date.getSeconds() = time_update’. If it wouldn’t require too much extra time and work .

    P.S. Your “Hotlink from Google” is missing ‘ type=”text/javascript”> ‘, someone unfamiliar with the syntax may get an error.

  5. Blog Author spacer Remy Sharp April 5th, 2011 at 7:37 pm

    @The_Anarchist – re: the “missing type attrib” – only the closing > was missing – the type attribute isn’t required as it’s consistently defaults to JavaScript in all browsers going further back than IE4 – so I’ve started stripping it.

  6. spacer Keith April 12th, 2011 at 8:14 pm

    Is it possible to not publish RTs?

  7. spacer goeck April 12th, 2011 at 9:42 pm

    Hello Remy,

    very nice and easy to use. One question, though: Is it possible to use the fetched tweets within the JS as a variable to reprocess the content using JS?

    THX

  8. spacer Josh April 14th, 2011 at 5:30 am

    Hi there, I am hoping you can help me with something. The “created_at” time is incorrect… I verified that my time settings on twitter are correct, I tried the google url and downloaded it to my server to self host as well with the same issue. I also verified that my time settings are correct in WordPress, and made sure that my server date and time are correct. I am at a loss.

    Do you have any suggestions.

  9. spacer dmmagic April 16th, 2011 at 4:53 pm

    I’m having a heck of a time getting Cufon text to style the tweets! I saw someone else pretty far up the comment chain was having the same problem, but I didn’t see if there was a solution. Is it even possible?

  10. spacer dmmagic April 23rd, 2011 at 7:28 am

    Any ideas, Remy?

  11. spacer Dave April 27th, 2011 at 3:03 pm

    hello, thanks for a great script :)

    is it possible to display re-tweets? has anyone figured out how to do this??

    many thanks

  12. spacer Matthew May 2nd, 2011 at 2:04 pm

    Is there a way in the template section of just getting the date in a format like
    27 Jun 11 or Mon 27 Jun without the time, or even better is there a way of getting day , month, year as separate variables?

  13. spacer Koen May 10th, 2011 at 12:38 pm

    For everyone trying to display retweets:

    search for ‘var url’ and replace the twitter url line with:


    var url = 'api.twitter.com/1/statuses/' + (options.withFriends ? 'friends_timeline' : 'user_timeline') + '.json?screen_name=' + id + '&callback=twitterCallback' + guid + '&count=20&include_rts=true&cb=' + Math.random();

  14. spacer Mark May 19th, 2011 at 9:33 am

    Hi Remy, great script, but as others have asked

    a) is it possible to get it too refresh automatically ?
    b) Could you expand the date formatting so we can format for ourselves, for example, allow us to add Time Zone, 24 hour etc.

    Many thanks

    Mark

  15. spacer TiPunK May 19th, 2011 at 3:45 pm

    Thanks a lot ! Very nice script !
    is it possible to change the date format ? I’m using for now the googlecode source.
    I would use it on a french website four youngs, and I’d avoid the ‘Created at’ sentence, or replace it with french terms, or at least place a readable date format.
    Thanks again.

  16. spacer Brian Enriquez June 5th, 2011 at 4:28 am

    Remi, thank you! I’ve been using this script for years now, but adding the spans inside the javascript template makes it invalidate using XHTML transitional:

    template: '%user_name% tweeted:"%text%"%time%'
    

    Can you offer another way to create styllable classes that validates?

  17. spacer zak June 6th, 2011 at 9:34 pm

    NewWindow parameter is not working

    getTwitters(‘tweets’, {
    id: ‘jbrandjeans’,
    count: 4,
    enableLinks: true,
    ignoreReplies: true,
    clearContents: true,
    newwindow: true,
    template: ‘%text% %time%‘
    });

  18. spacer Blues June 8th, 2011 at 10:58 pm

    How can I make the Twitters appear by word search? For example, my id is set to xrdnet, which displays tweets from twitter.com/#!/xrdnet.

    What if I want tweets from xrdnet, but only those tweets that contain the word “Japan”? Or any other specific word?

  19. spacer L June 10th, 2011 at 4:48 pm

    Remy-san,

    Great work! The tweets/retweets usually disappear after a couple of days because twitter.com does not store them longer. However, I have seen some sites like this www.fashionsnap.com/news/2011-06-07/beams-shitara-love where it keeps the tweets using scripts like yours. What can I do to prevent these tweets from disappearing?

    Thank you,
    L

  20. spacer Derek June 15th, 2011 at 5:33 pm

    Found the answer on another site. For Cufon text fonts to show you have to add a callback

    callback: function() {
    Cufon.replace(‘#tweet’);
    }

    groups.google.com/group/cufon/browse_thread/thread/afeaa1a0313c8d85

  21. spacer Miguel June 15th, 2011 at 11:48 pm

    This is great stuff.
    I’m just wondering how do you go about dealing with Twitter’s API limit request?

  22. spacer Luke June 16th, 2011 at 3:49 pm

    Hey Remy. Just wondering if you could help me figure out why the twitter code I put in loads in every browser perfectly, except for IE8, which loads it fine on every page but the homepage.

    protestintheusa.org

    I appreciate the help!

    Thanks,

    -Luke

  23. spacer Luke June 16th, 2011 at 5:27 pm

    Alright, well I got it to work. Instead of calling the hosted version from Google (twitterjs.googlecode.com/svn/trunk/src/twitter.min.js)

    I downloaded the latest 1.13.1 release, uploaded and called my own hosted version of the full ‘twitter.js’ (code.google.com/p/twitterjs/downloads/detail?name=twitterjs-1.13.1-release.zip&can=2&q=)

    Was anyone else having IE8 problems?

  24. spacer Luisa June 16th, 2011 at 8:56 pm

    It is possible setting multiple twitter accounts? How? If is not, you could take this as a suggestion :)

  25. spacer David Bless June 29th, 2011 at 9:47 pm

    Any idea how i can use Jquery cycle plugin with this?

    i would like to cycle 4 of my latest tweets – but the UL is wrapped in a DIV – which the UL could be the wrapper.

    has anyone tried this before? excellent stuff with this twitter.js file.. its really easy to use and style…

  26. spacer Gayle June 30th, 2011 at 1:51 am

    I’m working to adapt this for use with DNN. I’ll let you know if it’s successful! :)

  27. spacer David Bless July 1st, 2011 at 3:44 am

    WoW that would be excellent – looking forward to see what you come up with…

  28. spacer Ulf July 1st, 2011 at 5:31 pm

    Hi Remy, great script, impressive JS programming in the details.

    I’ve tried to modify it to have twitter search #hashtags instead of @ids. If I set the API call URL to search.twitter.com/search.json?q=…, twitter returns a different dataset, starting with twitterCallback1({“results”:[….

    How would your JS need to be modified to get rid of the results section, and process the search query result in lieu of the user status?

    Thanks in advance, Ulf

  29. spacer Lance July 4th, 2011 at 7:55 pm

    It appears that anchor tag links within the tweet %text% are being returned as null when using the template parameter. Any insight into this? Thanks!

  30. spacer NativePaul July 7th, 2011 at 1:58 pm

    This is such a great piece of code.

    How does this deal with the Twitter’s API call limit?
    It won’t load on any PCs on our office network – I’m assuming our server has made too many calls. How do we get around that?

gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.