Wednesday, September 29, 2010

Getting Twitter’s @Anywhere hovercards to work based on URLs

Twitter has a cool script you can add to your site to turn any references to a twitter account into a helpful hovercard that shows the twitter user, some stats, and a Follow button.  It’s subtle and useful, but it could be a little easier to add for developers.

I won’t repeat what is already available on the docs at Twitter, but the gist is if I put @kpespisa in a post, the @anywhere script will find that and turn it into a hyperlink that shows a hovercard when you put your mouse over the link. 

Sadly I noticed there was no simple way to get a hovercard to appear based on the URL of a hyperlink.  If I added a link that says “Follow me on twitter”, it would be nice to have the hovercard appear when I hover over that hyperlink as well. 

Adding a little jQuery gets the job done.  Using this code, you can just set the URL to and it will create a hovercard for you using the twitter account that is in the URL.

   1: <script src=""></script>
   2: <script src=";v=1"></script>
   3: <script type="text/javascript">
   4:     $(document).ready(function() {
   5:         $("a[href^='']").add("a[href^='']").attr("title", function() {
   6:             return '@' + this.href.substr(this.href.lastIndexOf('/') + 1);
   7:         });
   8:     });
  10:     twttr.anywhere(function(T) { 
  11:         T.hovercards(); 
  13:         T("a[title^='@']").hovercards({
  14:             username: function(node) {
  15:                 return node.title;
  16:             }
  17:         });
  18:     });
  19: </script>

For example:  Follow me on Twitter!

No comments: