Add Twitter to your blog (step-by-step)
Update - updated 25-Aug 2009
You can now directly hotlink from Google to remain up to date without having to change your script, see code below.
Hotlink from Google
<script
src="http://twitterjs.googlecode.com/svn/trunk/src/twitter.min.js"
type="text/javascript">
</script>
Download to self host
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"
- 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
lielement. 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%/">%time%</a>'
});
Template variables
All variables should be wrapped in % symbols (see the above example).
- text - the actual status message
- id - id of status message
- source
- time - relative 'friendly' time
- created_at - raw time
- user_name - real name
- user_screen_name - username
- user_id
- 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 download the twitter.js script or you can hotlink 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%/">%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.
You should follow me on Twitter here I'll tweet about JavaScript, HTML 5 and other such gems (amongst usual tweet-splurges)
Introducing HTML5
Okay, I just have one more small issue. I used CSS to remove the bullet, and margin-left: -40px to kill the indent, but that only works in Firefox. In IE, the negative margin causes the text to cut off. Is there a way to edit twitter.js to just get rid of the UL and LI elements altogether?
perfect
- THis was because i've too much trying before your first answer..
1) i've the same problem as HelloKit about indent.
2) What about the possibility to slowly hide the loading div and slowly show the loaded one with something like : http://github.com/madrobby/scriptaculous/wikis/effect-opacity
I've tried but don't see where to put some code but without acceptable results:
Code:
http://2009.mat.be/include/scripts/twitter_load.js
Results:
http://2009.mat.be/content.asp?id=welcome&theme=1
Thanks again... for you so helpfull advices
Mat
@Mat + HelloKit - indent:
#tweet ul { margin: 0; padding 0; } #tweet li { margin: 0; padding: 0; }then work from that. Good luck.Thanks. But you don't answer me to:
What about the possibility to slowly hide the loading div and slowly show the loaded one with something like : http://github.com/madrobby/scriptaculous/wikis/effect-opacity
Mat.
Thanks, Remy. I just finally figured that out on my own, but thanks so much for all your help! My badge now looks exactly the way it did before with the official Twitter badge, minus the annoying @replies, and with a cool "loading" animation. I love it!
Great code - saved me tons of load time - you can see it in action here: http://timothysykes.com
I just came back here and saw you updated the script. I replaced the script, however, the new script doesn't work for me. The tweets are not showing up. Can you help me please?
@Sarah - I should be able to. What the URL of the page?
I found the problem and got rid of it. I had to give the div an id name similiar to the name in the script.
Hi.
It's me again.
What about the possibility to slowly hide the loading div and slowly show the loaded one with something like : http://github.com/madrobby/scriptaculous/wikis/effect-opacity
I've tried but don't see where to put some code but without acceptable results:
Code:
http://2009.mat.be/include/scripts/twitter_load.js
Results:
http://2009.mat.be/content.asp?id=welcome&theme=1
Reagrds,
Mg
no more answer?
@Mat - as much as I hate saying 'no' - I don't have the time to write the upgrade you're requesting. If you want to have a crack, you need to edit the actual twitter.js code and change the line that delivers the UL:
what do you think about that:
http://2009.mat.be/content.asp?id=cv
regards,
Mg
@Mat - good work. I'd get a better matte on the spinner and it would be perfect.
Hi again.
I've a suggestion of update:
- setting a timout period after what somes action is possible: clearcontents, or displaying other things.. because lot of time twitter is down and is seems to load continuously..
Regards,
Mat
@Mat - with Twitter's recent outage that's exactly what I'm planning to do. Except with the advantage that even if the timeout is hit, the tweets could still load (depending on the browser timeout).
Watch this space.
I'm wondering if there's an easy way to paginate the results? I understand that the Twitter API limits requests to 20 at a time. It would be great if there could be an AJAX driven pagination to requests 21-40, etc.
Has anyone else tried this? Had success or failure?
Thanks in advance for any and all advice!
thanks, this was really helpful. now people don't have to wait for the sidebar to load my tweets before seeing the rest of the page load up.
@Mat. Love v1.10 for changing the max amount of tweets fetched, removing the 'too many replies' bug.
I think a timeout would be good. I've played with this before using a JavaScript timer with
_twitterTimer = setTimeout ('onTimeoutFunction()', 5000);on making the call to fetch the tweets andclearTimeout(_twitterTimer);on reaching a callback. With a function ofonTimeoutFunction()obviously updating the target with a 'failed' message (which is triggered after the time limit - in miliseconds). I had the feeling it was a little buggy however and there's probably a better way to do this.I'd also love to see some form of caching, this would improve loading time (obviously) and be a nice way to behave to the twitter server, but I'm not sure how this would be implemented! That's your job mister developer
Anyway, mucho thanks for the awesomeness again.
Thanks so much for this code. After some minor noodling this has accomplished exactly what I set out to plug in to my own site tonight, and I'm so very grateful for the work you did here. Keep it up.
As a side, (and I should mention I'm no programmer, so this might not be a great way to handle this...) I came up with a 'fake it' solution for the loader/timeout piece discussed here, to serve my own needs for the time being. I created an swf asset to drop into the progress indicator space, which cycles a loader graphic a few times then eventually lands at a "sorry, unavailable" type message. When twitter content loads it clears this out using your script, otherwise the 'sorry unavailable' message remains. Sample at kayos.com, upper right corner.
Thanks again, seriously.