Using Twitter’s @Anywhere Service in 6 Steps

Using Twitter’s @Anywhere Service in 6 Steps

Last week, Twitter released @Anywhere, which, with only a few added lines in your code, can bring all of Twitter’s platform functionalities into your website. @Anywhere can allow for anything, ranging from converting a simple @username into a clickable link, to even creating new tweets directly from your personal site. I’ll show you exactly how to do so in this tutorial!

Twitter Anywhere

Before you Begin, Create an Application

In order to begin using @Anywhere, you must have an API key. What? You don't have it? No problem. Just go here and register a new application  (don't register it from here).

  • If you have a local server installed, set it to a domain (developertutorial.com, for example), as it won't work with your localhost (if you don't know how, check out this tutorial, the hosts file part is particularly important).
  • If you don't have a local server, then leave this section blank. Just remember that for production, you will have to set it to the domain you are working on.

And finally, set the default access type to Read & Write. This is very important!

Now, you will be redirected to the application settings page. Copy the consumer key (API Key), and let's get started using @Anywhere.


Including @Anywhere's Javascript

Open your new HTML file, and, inside the <head> tag, include:

<script src="http://platform.twitter.com/anywhere.js?id=APIKey&v=1" type="text/javascript"></script>

Your code should look like:

<!DOCTYPE HTML>
<html>
<head>
<title>@Anywhere</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="styles.css" rel="stylesheet" type="text/css" />
<script src="http://platform.twitter.com/anywhere.js?id=APIKey&v=1" type="text/javascript"></script>
</head>
<body>
...
</body>
</html>

Replace APIKey with the Application's API Key you got in the previous step. The parameter v=1 is the version. Perhaps in the future, Twitter will add new features and maybe new syntaxes. To prevent breaking the existing @Anywhere code, they will be preserving old code if specified. Version 1 supports every major browser, including IE6.

After including this JavaScript file, we can access the twttr object, which will invoke the anywhere() function with a parameter when @Anywhere is ready:

twttr.anywhere(function(twitter) {
	// Actions when @Anywhere is ready
});

The parameter (in this case twitter) is the object we will be using, similar to jQuery's $.

Next, we need to create an HTML base. Copy and paste the following code, and place it within the “body” tag.

<div id="main">
	<div class="post">
		<h2>My blog post</h2>
		<div class="content">
			<p>This is a test blog post testing @Anywhere by @twitter.</p>
			<p>If you enjoyed this tutorial, please <a href="http://twitter.com/faelazo" class="hovercard">follow me</a> and keep in touch with @NETTUTS for more awesomeness.</p>
		</div>
	</div>
	<div class="comments">
	<h3>Comments</h3>
	<ol>
		<li><span class="author">@corcholat</span> says:
			<p>Such a great tutorial! </p>
		</li>
		<li><span class="author">@faelazo</span> says:
			<p>You should also follow @smashingmag</p>
		</li>
	</ol>
	</div>
</div>

Now let's dig in.


1. linkifyUsers: Convert @something into Links

@Anywhere lets us to convert @mentions into links. This functionality is called linkifyUsers, and is pretty straight-forward: it sets the HTML element you wish to convert to a link.

Since we want all the document's @mentions to be converted into links, we just call the linkifyUsers() function in the body element:

twttr.anywhere(function(twitter) {
	twitter("body").linkifyUsers();
});
linkifyUsers result

As mentioned previously, the “twitter” parameter, inside the callback function, is much like jQuery's “$” alias; f we want to convert @mentions into links, but only those within a certain section, we can use a CSS selector, as shown below.

twttr.anywhere(function(twitter) {
	twitter(".post").linkifyUsers();
});

linkifyUsers() accepts an object as a parameter, with two properties: className and success. With className, you can specify a class to be applied when the @mentions are found; so, for example, you could add an unsemantic 'red' class and specify in your CSS:

	.red { color:#f00; }

Here’s the code.

twttr.anywhere(function(twitter) {
	twitter("body").linkifyUsers({
		className:'red'
	});
});

2. hovercards: Display Additional Information on Hover

hovercards() converts @mentions to links, but also loads a small pop-up tooltip on mouseover. Here’s a basic example of its usage.

twttr.anywhere(function(twitter) {
	twitter.hovercards();
});
hovercards result

However, hovercards() is flexible enough to include certain elements even if they don't have a @mention in them. In the HTML, I'm linking "follow me" to http://twitter.com/faelazo; but @anywhere is smart enough to convert this link to a hovercard. By adding a class of “hovercard” to the anchor tag, Twitter will handle the rest!

twttr.anywhere(function(twitter) {
    // Find the @mentions and linkify as usual
    twitter("body").hovercards();
    
    // Let's find the elements which has a hovercard class
    twitter(".hovercard").hovercards({
        username: function(node){
            var twitter_regexp = /twitter\.com\/([a-z0-9_]*)\/?(.*)?/gi;
            if(node.href.match(twitter_regexp) && (twitter_match = twitter_regexp.exec(node.href))){
                return twitter_match[1];
            }
            return '';
        }
    });
});

The username parameter takes a function with a parameter that will be the object found (in this case node). Here's what happens inside the function, line by line.

var twitter_regexp = /twitter\.com\/([a-z0-9_]*)/gi;

This is a regular expression. It will match a twitter.com/ string with alphanumeric values and an underscore.

if(node.href.match(twitter_regexp) && (twitter_match = twitter_regexp.exec(node.href))){

If the regexp matches the href property from the node element, then set the variable twitter_match to capture the values in an array.

return twitter_match[1];

It will return the match found.

We add a “return” just in case the element does have a class, but does not refer to twitter.com; so there will be no match. If it returns false or NULL, the script throws an error. With an empty string, it shows a hovercard but with no user found.

Now, if this is a bit too complicated, you can always simplify the process, and add the username as the title attribute of the anchor tag.

<a href="http://twitter.com/faelazo" class="hovercard" title="faelazo">follow me</a>

And just return the node‘s title attribute. Much easier, right?

twitter(".hovercard").hovercards({
    username: function(node){
        return node.title;
    }
});

“hovercards” can be applied to any element (even a div), just as long as it specifies a username.

twitter("#main").hovercards({ username: function(){ return 'therrorcom'; }});


3. followButton: Invite to Follow with Just One Click

followButton() will append a button to follow the username parameter in the element previously specified.

The following code will append a button to follow Nettuts+ in the #main div.

twttr.anywhere(function(twitter) {
    twitter("#main").followButton("nettuts");
});
followButton result

followButton() expects one parameter: the username to follow. Simple enough, eh?


4. tweetBox: Tweets From your Site

tweetBox() will append a box in which the users can enter their comments and tweet them via your site.
tweetBox can receive an object as parameter, with the following properites:

  • counter (boolean, default true)
    Whether or not to show the counter for remaining characters.
  • height (integer, default 65)
    The height of the box, in pixels.
  • width (integer, default 515)
    The widht of the box, in pixels.
  • label (string, default "What's happening?")
    The text above the box.
  • defaultContent (string, default none)
    You can enter by default the URL, a @mention, a #hashtag, etc.
  • onTweet (function)
    It's called after the tweet button is pressed. It receives two arguments: plain text tweet and HTML tweet.

A default tweetBox can be called after the element with the comments class with the following snippet.

twttr.anywhere(function(twitter) {
    twitter(".comments").tweetBox();
});

So if you want a custom label, content, and a callback when the tweet has been sent, use this code.

twitter(".comments").tweetBox({
    label: 'What do you think about this article?',
    defaultContent: '#nettuts ',
    onTweet: function(plain, html){
        // Actions when tweet is sent
    }
});
custom tweetBox result

onTweet might be useful if you are planning to replace the default comment area with the CMS you are using. You would still need a database and a table to show the comments, right? So you can hack the CMS a little and make a AJAX request with the onTweet event to insert the tweet into your database.


5. connect: Sign in a User to your Application

As you probably saw, the two last methods require confirmation to grant permission to the application. @Anywhere has a method to check if the user is logged in with the application (not on twitter). You can use conditionals to whether or not to show certain elements.

This snippet will append the connect button in the element with a comments class.

twttr.anywhere(function(twitter) {
	twitter(".comments").connectButton();
});
custom tweetBox result

If you need a button with a different size, you can pass an object literal with the property size and value small, medium, large or xlarge. Note that “medium” is the default value.

twttr.anywhere(function(twitter) {
	twitter(".comments").connectButton({ size: 'large' });
});

The Twitter object includes some extra goodies; one is currentUser, which is an object; the other is isConnected(), which is a function that returns a boolean. From here, we can create some conditional statements.

twttr.anywhere(function(twitter) {
	if(twitter.isConnected()){
		alert('Welcome, you are connected');
	} else {
		twitter(".comments").connectButton();
	}
});

If isConnected() returns true, we can show some user information, such as the username (screen_name), profile picture (profile_image_url), followers or following. Here's a list for the information that the application can access. Let's see the currentUser object in the final roundup.


6. Final Roundup: Mixing it All Together

I will be modifying the div with the comments class.

<div class="comments">
	<h3>Comments</h3>
	<ol>
		<li><span class="author">@corcholat</span> says:
			<p>Such a great tutorial! </p>
		</li>
		<li><span class="author">@faelazo</span> says:
			<p>You should also follow @smashingmag</p>
		</li>
	</ol>
	<div class="add">
		<h3>Add comment</h3>
		<div class="author"></div>
		<div class="box"></div>
	</div>
</div>

Now let's include jQuery to make things a bit easier. Insert, between <head> and </head>, the following code:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>

Now we have a space to add comments. First, let's use the isConnected() conditional to show a button if the user is not signed into our application; this button will be appended to the element with an "add" class.

if(twitter.isConnected()){
    twitter(".comments").connectButton();
}

Now let's use Twitter’s currentUser object. This object can retrieve information with the data() method. So the following snippet will retrieve the user's screen_name.

twitter.currentUser.data('screen_name');

@Anywhere lets us specify callback functions for the connectButton feature. As an argument, it accepts an object with two properties: authComplete and signOut; both are functions, so when signOut is invoked, we could refresh the page. The same holds true for authComplete. Let's replace the connectButton() line with this snippet:

twitter(".comments > .add").connectButton({
    authComplete: function(user) {
        location.reload();
    },
    signOut: function() {
        location.reload();
    }
});

This is pretty straightfoward: we pass an object as the argument, then set both the signOut and authComplete functions to reload the page. Note that I've dropped the else clause for the isConnected() conditional in order to set the signOut event.

Next, let's add a tweetBox inside the conditional.

if(twitter.isConnected()){
    $(".comments > .add > .author").html('<img src="'+ twitter.currentUser.data('profile_image_url') +'" /> <a href="http://twitter.com/'+ twitter.currentUser.data('screen_name') +'">'+ twitter.currentUser.data('screen_name') +'</a> | <a href="javascript:twttr.anywhere.signOut();">Sign out</a>');
    twitter(".comments > .add").tweetBox({
        label: 'What do you think about this article?',
        defaultContent: '#nettuts '
    });
}

If the user is logged in, a follow button should be there. Again, inside the conditional:

twitter(".comments > .add").followButton("nettuts");

Here is the whole conditional, rounding up all of the @Anywhere features.

if(twitter.isConnected()){
    $(".comments > .add > .author").html('<img src="'+ twitter.currentUser.data('profile_image_url') +'" /> <a href="http://twitter.com/'+ twitter.currentUser.data('screen_name') +'">'+ twitter.currentUser.data('screen_name') +'</a> | <a href="javascript:twttr.anywhere.signOut();">Sign out</a>');
    twitter(".comments > .add").tweetBox({
        label: 'What do you think about this article?',
        defaultContent: '#nettuts '
    });
    twitter(".comments > .add").followButton("nettuts");
}
Final roundup


Conclusion

@Anywhere is obviously Twitter's response to Facebook Connect. They’re hoping to bring this platform to as many sites on the web as possible; and while the service is still young, and the documentation could definitely be improved, it’s definitely promising! Please show us what you’ve done with @Anywhere in your own websites!

Rafael Soto is faelsoto on Codecanyon
Tags: Twitter
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://xpressabhi.com abhishek

    I am using this feature on my blog.
    I like it.
    Your explanation is very good. Twitter should provide your post link on their site so people can easily find this post.
    Thanks.

    • http://xpressabhi.com abhishek

      Hi,
      A months back when I wrote on my blog about this (twitter anywhere). I was quite right. Have a look here..

      http://xpressabhi.com/twitter-will-be-now-anywhere/

    • Raf1k1

      Can this be customised as in can I change the colour or use my own buttons to fit the colour scheme of my site?

  • http://ipadappshub.com Brad Mahaffey

    Very nice, can’t wait to integrate this functionality into my blog.

  • http://aaronbentley.co.uk Aaron Bentley

    Very nice tut! i hope to use @Anywhere in future projects :)

  • http://psdho.me PSDhome – Everyday free PHOTOSHOP files

    Great post. Great tutorial. Thanks a lot…

  • http://www.smashingshare.com Smashing Share

    Nice one. Would definitely try this.

  • http://sideradesign.com paul

    nice, I’ll probably use it on my next projects

  • http://yagua-piru.posterous.com/ robert

    Awesome Rafael, and I agree with @abhishek Twitter should provide your post link, you have explain much clear that Twitter… :D

    Rafael, la verdad que @abhishek tiene razón con el tema que Twitter tendría que poner este link para explicar el tema de @Anywhere por la verdad que lo hiciste bastante claro… “Mas claro que el agua!” ;)

    All the best

  • http://technetic.org Paul

    I like the direction this is headed with both Facebook and Twitter. Both using OAuth now, and providing amazingly simple APIs to integrate an awesome social experience on your website.

  • http://ds.laroouse.com esranull

    hala bunun ne işe yaradığını anlamış değilim

  • http://www.engram.nu Niklas

    Great stuff. Thanks for this.

  • http://www.myunv.com/ Sunny Singh

    Wish I’ve seen this before trying to figure out the poor documentation Twitter has. Not much of a JS developer so the isConnected vs isConnected() really got me.

    Anyways, here’s what I integrated it into: http://music.myunv.com/exclusives/music-monday/

  • http://www.oe-design.com/ Danny Dyson

    Bookmarked! Im currently in the middle of re-designing my blog and will definitely use this in the new design.

  • http://neodeva.com mdennisa

    great tuts, maybe rafael should follow up this tuts with another such as “using facebook connect in 6 steps” so we can compare :)

    thanks!

    • http://www.poop.com Hello Kitten

      This is a great blog. I need to see more of it.

  • http://www.jsxtech.com Jaspal Singh

    Great tutorial for beginners using Twitter’s @anywhere service.
    Thanks for sharing.

  • http://www.crearedesign.co.uk Stephen Webb

    This is an interesting but not unexpected development from Twitter. Lately Facebook has been developing its ability to integrate with websites and it was only a matter of time until Twitter followed suite.

    Reading through the steps it does seem relatively straight forward to implement this new feature into an existing website, and I can certainly see it taking off soon.

    The web is becoming a much more social environment and features like this will become more common as this progresses. It will be interesting to see if Facebook unleashes another product to counter-act this, as the two are the major players in the social networking world.

  • http://sonergonul.com/ Soner Gönül

    Wow

    That’s wonderful

    Thanks.

  • http://www.pistapera.com Jonatha

    I’ve seen than including twitter.js an IFrmame is added to the page, there’s a way to avoid it?

  • http://nikhilmisal.com Nikhil

    Great use. Gonna implement one of these in blog!
    :)
    Thanks for sharing!

  • Dave

    Does anyone know if this will this provide an easier method of converting http:// URLs and @username URLs to clickable links in Flash?

    Using RegEx for this is a royal pain!

  • http://francoaverta.com.ar/blog Franco

    Thanks!, I Would definitely bookmark this one for my site redesign!

  • http://cookyx.com Dan

    Wow!! Definitely gonna try this for my new site’s v4 update!! Thanks a lot man! You’re awesome.

  • http://www.myastrodata.com/ Vladimir Komarov

    Twitter @anywhere seems like an answer for some of my questions. Thank you very much for this quite useful tutorial.. and Netttus FTW :] I’m gonna use @anywhere soon, definitely!

  • http://www.therror.com Rafael Soto

    Thanks for your comments guys, I am very pleased you found it useful.
    abhishek, thanks, the official documentation sadly is a bit confusing. I hope they either fix it or link this post.
    robert, la verdad me eché un clavadote al código fuente para más o menos entender la documentación porque tenía bastantes errores. Gracias por tu comentario.
    Sunny Singh, yeah, I had to look in the source code to find out why it wasn’t firing up. Turned out it was not a property but a method!
    mdennisa, well, Facebook Connect’s features aren’t just six! But yeah, I will look into the documentation to see if I can compare something. Great idea, thanks.
    Jonatha, I don’t think so.

  • http://DeanMarkTaylor.com Dean Taylor

    Here is a simple regular expression example to add @Anywhere Hover Cards existing links:

    twttr.anywhere(function(T) {
    T.linkifyUsers();
    T(“a[href^=http://twitter.com/], a[href^=http://www.twitter.com/]“).hovercards({
    username: function(node) {
    return node.href.replace(/http:\/\/(?:www\.)?twitter\.com\/([^\/]+).*/img, “$1″);
    }
    });
    });

    Although it should be noted that this assumes that everything after “http://twitter.com/” until the next “/” is a username. As such will attempt to add hovercards to the rarely linked pages like: http://twitter.com/about.

    This also works correctly and adds hover cards to status links like this one:
    http://twitter.com/DeanMarkTaylor/status/12697858812

    Hope this helps,
    Dean.

    • http://orangkucing.tumblr.com/ orangkucing

      I think the following is better. Because regexp is slow and, when it fails, returning null is the worst idea.

      twttr.anywhere(function (T) {
      T.hovercards();
      T(“a[href^=\"http://twitter.com/\"]“).hovercards({
      username: function (node) {
      var m;
      for(;;) {
      if (node.href != undefined) {
      m = node.href.split(“/”);
      if (m[2] == “twitter.com”)
      return m[3];
      }
      node = node.parentNode || node.parent; // for IE
      }
      }
      });
      });

      I ignore http://www.twitter.com/.* links but you can add if you like.

      Note: This code should locate near the end of page if your page has some dynamic contents such as DISQUS.

  • Jim

    So how does this interact with the API limits Twitter has? Do you need to cache calls, does it handle all of this on the backend so you could place this on an extremely busy site and it wont kill your connection to twitter for excessive pulls?

  • http://articles4business.info/ Agent de bord

    Yes it’s useful to use Twitter’s @anywhere service.
    Thx
    Great Site

  • melih orhan

    It is wonderfull.
    Thanks

  • http://www.watchingthetigers.com Chad

    Thanks. Plugged @anywhere into this twitter/location/sports page I made for myself. http://www.watchingthetigers.com It seems to work.

  • http://www.dumidesign.com dumidesign

    nice Application!! im going to use dis for my site.thanks!

    Dumidesign
    http://www.dumidesign.com

  • http://cdnpic.com mahesh

    its nice feature..I have implemented on my site

  • http://www.music-explained.com John Barnes

    I take it there is no way to update your status without using the tweetbox?
    for example

    twttr.anywhere(function (T) {
    t.updateStatus(‘update my status’)
    });

  • Daniel

    Is there a way to connect with @anywhere and to post comments on blogs or smth?

  • http://treasurezone.de TreasureZone

    I will try @anywhere soon. Thanks for this tutorial.

  • sct

    I ended up getting it working in everything but Opera. Funny how its supposed to have the best javascript engine.. but its failed on javascript all across the web.

  • http://www.catgirlalexandria.wordpress.com Laura

    That’s an awesome tutorial, I definitely will play with this in my next project. Thanks for the tut!

  • http://dignesa.com Serhan Buyukiscan

    Dude, this is an awesome guide. I was looking to find a way for my visitors to share a tweet directly from the site. You just made my day. Thanks

  • Jo Dean

    Wow, that is the coolest thing I ever seen.

    Lou
    http://www.vpn-anonymity.us.tc

  • http://www.adhiemempawah.blogspot.com bang adhie

    good post, tank for this article. i like it

  • http://www.1000niaz.com 1000niaz نيازمنديها

    Thanks!, I Would definitely bookmark this one for my site redesign!

  • http://mridul.co.in Mridul

    Any idea if it is possible to add events to the text area ? For example, when someone is typing on the twitter textbox, I would like to add normal javasript events to it…. ?

  • http://www.sjlwebdesign.co.uk SJL Web Design

    This looks really awesome!! Can’t wait to try it out!

    Thanks.

  • http://www.computerman.gr/ Petsoukos

    I can’t get the “Follow @MySite” button/service to work… I get:

    Sorry, something went wrong.

    The provided callback url http://betamin.gr/index.php is not authorized for the client registered to ‘http://www.betamin.gr/’.

    I use Joomla and added the Javascript directly into the tags and added an empty custom HTML module with class suffix _blank follow

    twttr.anywhere(function(twitter) {
    twitter(“.follow”).followButton(“betamingr”);
    });

    The button loads but I get the previously mentioned error..

    • http://www.vinayvidyasagar.com Vinay Vidyasagar

      I have the same issue – Can someone clarify this. How do I edit the callback url -

      • http://www.vinayvidyasagar.com Vinay Vidyasagar

        Ok That was stupid enough. I found the solution. Quite simple actually.

        in your twitter application, you need to change the type from “client” to “browser”. Then you’re given another line asking you for the callback url – You have to specify http://www.yoursite.com/ in there and make sure your other two urls are exactly the same. Hope this helps.

  • http://www.digital-mr.com Chris

    I like that tool a lot. But i am really wondering if its right to use in a website that is for everybody a functionality that works for the twitter. what about visitors that don’t use twitter?
    But anyhow it is a great and easy way to interact ur website with twitter and get some traffic!

    WELL DONE :)

  • Nomad A.

    I am really new at this so please bare with me. is it possible to do the following:

    1) twitterlogin.php where you login with twitter account using Oauth ofcourse (say the twitter username is CookieMonster) just like in the highlighted example of abraham’s twitteroauth – GitHub

    2) Display tweets from the username CookieMonster

    3) if the user wants to tweet then redirect the user to a twitter.php page where there is a form or tweetbox so the logged in user can tweet in the post as if he is “CookieMonster”. if the tweet is succuessful then echo “successful” if the tweet did not go thru then echo “Error. Tweet was not sent. Try again!”

    I have an app registered with twitter and was able to authenticate using Oauth but don’t know how to perform #2 and #3

    your help is much appreciated. thx

  • http://jaron.nl jaronbarends

    As for using this on your local server: for me this simply works when Im using http://127.0.0.1/path/to/page.html as callback url (as long as Im also putting the tweetbox within 127.0.0.1, and requesting that page through http://127.0.0.1 and not through http://localhost). Using http://localhost.path/to/page.html does not work.

    I have not yet seen a way to send the callback url as a parameter with wi
    Just remember to change the callback url before you go live!

  • http://jaron.nl jaronbarends

    Didn’t properly finish my sentence in my reply, and I was going to give wrong information, too. You can’t just set the callback-url in your settingspage, you can also configure it in your javascript. http://dev.twitter.com/anywhere/begin#custom-callback. Before you call twttr.anywhere(), use this: twttr.anywhere.config({ callbackURL: “http://www.yoursite.com/anywhere-complete” });

  • Subrat

    Hi,

    i want to show all of my tweets in iphone using tweeter engine.

    please help me regarding this.

    Thanks
    Subrat

  • http://www.unknown.com Ahmad

    Thanks for sharing this Tutorial for people like us, poor beginner… I try to used this method I don’t know something going wrong not worked for me… Can you please please collect all code same as facebook connect source so we can easily know what to do.

    thanks

  • Johnny

    Has anyone run into rate limit issues? Any tips on how to use local cache for saving requests?

  • Roger

    hi, your code for Final Roundup: Mixing it All Together doesn’t work at all, just the first part for the connect button doesn’t work, and nothing appear, this is why you should alway include a demo page