I’ve added a twitter “bezel” to the top of my weblog. Here’s how it works:
First, I inserted a new div at the very start of the HTML, which will hold the text of the most recent tweet, but will at first show a progress indicator:
<div name="bezel" id="bezel" onclick="location.href='http://twitter.com/csm'"><img src="/images/concern/indicator.black.gif" alt="loading twitter..." /></div>
The bezel will have a nice smoke colored background, and will use some small, white text (Helvetica, naturally). We’ll put it at the top of the page, a short distance from the right edge. The CSS that does this:
div#bezel
{
position: relative;
top: 0;
right: 50px;
float: right;
color: white;
font-family: Helvetica, Arial, sans;
font-size: xx-small;
padding: .5em;
width: 273px;
background-image: url(http://metastatic.org/images/concern/TwitterBezel.png);
background-position: bottom left;
background-repeat: no-repeat;
line-height: 110%;
}
Twitter provides a nice way to access tweets via JSON — that is, as JavaScript. So what we’d like to do is load the most recent tweet via JavaScript, and if the tweet can be loaded, replace the progress indicator with the tweet. Now, browsers rightly won’t let you make an XMLHttpRequest to other web sites, so we add a PHP file that does the request to the external site. This example is rather specific to Dreamhost, since they disable readfile of a URL:
<?php
$ch = curl_init();
$timeout = 5; // set to zero for no timeout
curl_setopt ($ch, CURLOPT_URL, 'http://twitter.com/statuses/user_timeline/csm.json?callback=twitterCallback&?callback=twitterCallback&count=1');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec ($ch);
curl_close($ch);
// display file
echo $file_contents;
?>
Then, in our HTML we add the JavaScript code, setting the onload event to call twitter_bezel:
<script language="javascript">
var request;
function twitterCallback(value)
{
document.getElementById('bezel').innerHTML = value[0]["text"];
}
function twitter_bezel_callback()
{
if (request.readyState == 4)
{
var newText = 'twitter status failed to load.';
if (request.status == 200)
{
try
{
eval(request.responseText);
}
catch (e)
{
document.getElementById('bezel').innerHTML = newText;
}
}
else
{
document.getElementById('bezel').innerHTML = newText;
}
}
}
function twitter_bezel()
{
try
{
if (window.XMLHttpRequest)
{
request = new XMLHttpRequest();
}
else
{
request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.onreadystatechange = twitter_bezel_callback;
request.open('GET', 'http://metastatic.org/text/Concern/wp-content/themes/Barthelme.mine/wp-twitter.php', true);
request.send(null);
}
catch (e)
{
document.getElementById('bezel').innerHTML = 'twitter status failed to load.';
}
}
</script>

Loading...
Post a Comment