bit.ly javascript button

Hello everyone!

I took quite a long time to figure this simple thing out. It annoyed me so much that all I could get was a twitter button share with bit.ly that I decided to publish my solution here.

The solution was partially done using the API example at http://code.google.com/p/bitly-api/wiki/ApiExamples. (You can diff the texts to spot the differences 😉 )

See a demo in action

My solution is below:

<html>
 <head>
    <title>Bitly Link Example</title>
    <style>
      .showLink{background:#fffedf; border:1px dashed #d9d596; display:inline-block; padding:10px;}
      .shortme{background:#f1f1f1; border: 1px solid #ccc; padding:5px;}
      .shortme:hover{boder:2px; background:#e0e0e0;cursor:pointer;}
    </style>
 </head>
 <body>
    <h1>bit.ly button to short current page</h1>
    <p>Just click on the button below to get a shorten url of this page</p>

    <!-- Instead of button, a text link: <a href="#" class="shortme">Get short URL</a> -->
    <input id="btn" value="Get short URL" type="button" class="shortme"><br>

    <script type="text/javascript" charset="utf-8" 
    src="http://bit.ly/javascript-api.js?version=latest&login=YOUR_BITLY_LOGIN_HERE&apiKey=YOUR_BITLY_API_KEY_HERE">
    </script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>

    <script>
        var shortThisLink = {
            shorten : function(e) {
                // this stops the click, which will later be handled in the response method
                e.preventDefault();
                // gets current location (URL)
                var url = window.location; 
                BitlyClient.shorten(url, 'shortThisLink.response');
            },    
            response : function(data) {
                var bitly_link = null;
                for (var r in data.results) {
                    bitly_link = data.results[r]['shortUrl']; 
                    break;
                }
                var myshorturl = bitly_link
                // prints short link on page
                document.getElementById("short").innerHTML=myshorturl;
                // gives some style just to highlight the short link created
                document.getElementById("short").className += "showlink";
            }
        }
        jQuery('.shortme').bind('click', shortThisLink.shorten);
    </script>
    <br>
    <div id="short"></div>
 </body>
</html>