Join our FREE Fastrack Webinar this Friday!

How to connect your site with twitter using @Anywhere

Posted in Tutorials4 years ago • Written by 10 Comments

Twitter has launched @Anywhere, a more simple way of integrating twitter in your site. With it you can add follow buttons, hovercards, linkify twitter usernames and connect with twitter.  In this tutorial, I will show you how to use @Anywhere in your site. I will add some twitter @Anywhere features to the application build in my previous tutorials, the distance finder (part1 of the tutorial, part2).

What are we going to build?

The distance finder we created using the previous tutorials uses the google maps api to let you find the distance and route between two locations. In this tutorial, I’ll show you how to share your search results with your twitter followers. I’ll also show you how to add hovercards and linkify usernames.

You can view the demo here. And also download the source code.

Prerequisites

The first thing we need to do in order to use @Anywhere is to registered a new twitter application. We can do this here. Once we fill in that form, we will be given an APIkey to use in the app.

Next, we’ll have to include the @Anywhere script. We’ll add the following code to your <head>section:


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

Don’t forget to fill in the api key!

As some of the options from @Anywhere require jquery, we will have to include that too:


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


Adding a comment box

Let’s see what we need to add to show a small comment box to help us share the search results with our friends.

We’ll have to add another div to the layout, where to show the comment box with the text to share with our friends.


<center><div style="width:100%; height:13%"></div></center>

In the javascript function that shows the route (called continueShowRoute) we will have to add some code to show the comment box.

//we have to create a div where @Anywhere will place the comment box; the div will be created inside the share div
var twitter = "<div class='comments'></div>";
document.getElementById("share").innerHTML = twitter;
// we’ll call the share_twitter function with the two addresses as parameters.
share_twitter(address1, address2);

The share_twitter function is used to create the link to share with our friends and show the comment box.

The code which uses @Anywhere to show the comment box is pretty simple. It looks like this:

twttr.anywhere(function(twitter) {
   twitter(".comments").tweetBox({
      label: 'Share with your twitter friends!',
      defaultContent: 'My search on distancefinder: '+url,
      height: 30
   });
});

It calls the anywhere function for the twttr object and passes the tweetBox function as a parameter.  The comment box will be shown in the div with the id given as parameter (“.comments”). We can set the following options for the comment box:

  • Label: the text to be shown above the box
  • DefaultContent: the content of the box
  • Height, width: the boxes dimensions
  • Counter: whether or not to show the counter for remaining characters
  • OnTweet: a function to be called when the tweet button is pressed.

We will also have to share the link to the current page. We’ll also have to add the two address values to the url to be able to share a search result. This way, when the friend clicks on our link, they will be redirected to the application page with the addresses set and see our results. We will use PHP Get to pass the two addresses.

As the url might get too long for a tweet, we’ll have to shorten it. For this we can use tinyurl to obtain a shorter url address. To do this, we have to make a request to:


<a href="http://tinyurl.com/api-create.php?url=THE_LONG_URL">http://tinyurl.com/api-create.php?url=THE_LONG_URL</a>

We’ll make a php script that receives an url address, sends a request to tinyurl.com and returns the result.  We’ll store it in the file called getShortURL.php. The script looks like this:

<?php
$url = $_GET['url'];
echo file_get_contents("http://tinyurl.com/api-create.php?url=" . urlencode($url));
?>

We’ll have to call this script using ajax from our share_twitter function and, when we get the result from the script, show the comment box from @Anywhere.

Here’s how the code for this looks like:

var xmlhttp;
function share_twitter(a1, a2)
{
  var my_url = location.href;
  if (my_url.indexOf('?a1=') != -1)
  {
    my_url = my_url.substr(0, my_url.indexOf("?"));
  }
  my_url += "?a1="+a1+"&a2="+a2;

  xmlhttp=GetXmlHttpObject();
  if (xmlhttp==null)
  {
    alert ("Browser does not support HTTP Request");
    return;
  }
  var url="getShortURL.php";
  url=url+"?url="+encodeURIComponent(my_url);

  xmlhttp.onreadystatechange=stateChanged;
  xmlhttp.open("GET",url,true);
  xmlhttp.send(null);
}

function stateChanged()
{
  if (xmlhttp.readyState==4)
  {
    twttr.anywhere(function(twitter) {
      twitter(".comments").tweetBox({
         label: 'Share with your twitter friends!',
         defaultContent: 'My search on distancefinder: '+xmlhttp.responseText,
         height: 30
      });
    });
  }
}

Here’s what the share_twitter function does. It first get the url of the current page:

var my_url = location.href;

If there are already some variables set in PHP GET it erases them and adds the new values (a1 and a2, the functions parameters)

if (my_url.indexOf('?a1=') != -1)
{
  my_url = my_url.substr(0, my_url.indexOf("?"));
}
my_url += "?a1="+a1+"&a2="+a2;

The rest of the code is a bit more complicated (also, I’ve not shown here the GetXmlHttpObject function; you can see it in the source code), but you don’t have to worry if you don’t get it! All you need to do is that it is used to make the request to the getShortURL.php script and receive the result. When it gets the result (if (xmlhttp.readyState==4)) it calls the @anywhere code to show the comment box and sets the url value to the short url it received.

We will also have to add a few lines of code to our app, to be able to load our friends search results. As I said, we have sent the a1 and a2 parameters (the two addresses) through GET. We will have to add a script to check if the variables are set and if they are, to show the correct map.

We will add this php code before the </body> tag:

<?php
if (isset($_GET['a1']) && isset($_GET['a2']))
{
   echo "<script>start('".$_GET['a1']."', '".$_GET['a2']."');</script>";
}
?>

As you can see, the script will call the start function if the two parameters are set. Let’s see how the start function looks like:

function start(a1, a2)
{
   document.getElementById("address1").value = a1;
   document.getElementById("address2").value = a2;
   initialize();
}

All it has to do is set the address values in the textboxes and to call to initialize() function, the one that shows the map.

And that’s it! We now have a comment box in our app. Of course, the users will have to be logged in their twitter accounts and allow your app to connect to their accounts. But all this is taken care of by @Anywhere!

Let’s check out other features of @Anywhere:

Linkifying twitter usernames

With only a few javascript lines added to the head section of your site, @Anywhere will convert all twitter usernames on your page in links to the proper twitter profiles.

Here’s the script we need to add:

twttr.anywhere(function (T) {
   T.linkifyUsers();
});

You just have to call the linkifyUsers() function. This code will turn all twitter usernames found in the <body> section to links. You can also chose to only linkify the usernames in a section of your site. To do this, you will only need to specify the id of the element which has the usernames you want linkified.

twttr.anywhere(function (T) {
   T("#ELEMENT_ID").linkifyUsers();
});

Hovercards

Hovercards are small tooltips that show some data about a particular Twitter user. These will show up if you go with the mouse over a twitter username on you site. To add this option, you will have to add this script:

twttr.anywhere(function (T) {
   T.hovercards();
});

You can also limit the scope when the hovercards appear, just like with linkifying usenames.

Let’s add a twitter username to the site and test these features:

<center><div style="width:100%; height:4%">Demo App by @anirib</div></center>

@Anywhere seems pretty cool, eh?

If you enjoyed this article, get email updates (it's free).

Join over 81,746 Subscribers Today.

7 Written ArticlesWebsite

Irina is a software developer from Bucharest, Romania. She enjoys working on various programming projects. She likes spending her spare time reading, hiking, travelling, skating or playing tennis. She also blogs a bit. You can find her online in her home on the internet and on twitter.

10 Comments Best Comments First
  • SaVonni Yestanti

    Wednesday, August 18th, 2010 07:08

    1

    Thank you so much for this tutorial! I can’t wait to try it! :-)

    0
    • Irina

      Wednesday, August 18th, 2010 17:24

      2

      I hope you’ll enjoy working with @anywhere!

      0
  • Jay Henderson

    Wednesday, August 18th, 2010 19:39

    5

    What would be nice is if twitter api developers could create a way to track the @Anywhere links inside CMS’ or a analytical version within twitter. I think it would be beneficial to see whose implementing your twitter handle into your website and what’s the rate of users that are following you from that link suggestion within other sites? Do you guys think that would be interesting as a side feature?

    0
    • Irina

      Thursday, August 19th, 2010 09:48

      6

      Yeah, it would be a good idea for them to add some sort of analytics!

      0
  • bassam samy

    Thursday, September 16th, 2010 22:16

    7

    thanks for sharing :)

    0
  • Kori Viens

    Friday, October 14th, 2011 12:50

    10

    We’re a gaggle of volunteers and opening a brand new scheme in our community. Your website provided us with helpful info to work on. You have done an impressive activity and our whole group shall be grateful to you.

    0
  • Tomas

    Monday, September 12th, 2011 18:13

    9

    Thanks for sharing. But I would appreciate if you could do a screencast for novices like me. I can’t even tell where to add some of the codes you displayed above.
    I hope you’ll be able to do this.
    Thanx

    0
  • tande

    Tuesday, May 31st, 2011 22:01

    8

    what if the platform your designing your website from is iWeb

    0
  • John Paul

    Wednesday, August 18th, 2010 16:25

    3

    What a briliant idea ,thanks for sharing this info mate .

    -1
    • Irina

      Wednesday, August 18th, 2010 17:23

      4

      No problem, I’m glad you liked it!

      -1
  • Kori Viens

    Friday, October 14th, 2011 12:50

    10

    We’re a gaggle of volunteers and opening a brand new scheme in our community. Your website provided us with helpful info to work on. You have done an impressive activity and our whole group shall be grateful to you.

    0
  • Tomas

    Monday, September 12th, 2011 18:13

    9

    Thanks for sharing. But I would appreciate if you could do a screencast for novices like me. I can’t even tell where to add some of the codes you displayed above.
    I hope you’ll be able to do this.
    Thanx

    0
  • tande

    Tuesday, May 31st, 2011 22:01

    8

    what if the platform your designing your website from is iWeb

    0
  • bassam samy

    Thursday, September 16th, 2010 22:16

    7

    thanks for sharing :)

    0
  • Jay Henderson

    Wednesday, August 18th, 2010 19:39

    5

    What would be nice is if twitter api developers could create a way to track the @Anywhere links inside CMS’ or a analytical version within twitter. I think it would be beneficial to see whose implementing your twitter handle into your website and what’s the rate of users that are following you from that link suggestion within other sites? Do you guys think that would be interesting as a side feature?

    0
    • Irina

      Thursday, August 19th, 2010 09:48

      6

      Yeah, it would be a good idea for them to add some sort of analytics!

      0
  • John Paul

    Wednesday, August 18th, 2010 16:25

    3

    What a briliant idea ,thanks for sharing this info mate .

    -1
    • Irina

      Wednesday, August 18th, 2010 17:23

      4

      No problem, I’m glad you liked it!

      -1
  • SaVonni Yestanti

    Wednesday, August 18th, 2010 07:08

    1

    Thank you so much for this tutorial! I can’t wait to try it! :-)

    0
    • Irina

      Wednesday, August 18th, 2010 17:24

      2

      I hope you’ll enjoy working with @anywhere!

      0

Comments are closed.

54.81.76.245 - unknown - unknown - US