bit.ly via jsonp and mootools

by Dimitar Christoff

HTML

<h1>A JSONP class to shorten urls via bit.ly:</h1><br/><br/>

<a href="http://news.bbc.co.uk/sport1/hi/football/europe/8797183.stm">http://news.bbc.co.uk/sport1/hi/football/europe/8797183.stm</a><br/>
<a href="http://fragged.org/">http://fragged.org/</a><br/>
<a href="http://fragged.org/code-your-own-facebook-be-the-first-to-like-with-mootools_1095.html">http://fragged.org/code-your-own-facebook-be-the-first-to-like-with-mootools_1095.html</a><br/>
<a href="http://ibm.com/">http://ibm.com/</a><br/>

<br/><br/>

for exmple's sake, a .shortened class is applied to links that have been modded to use bit.ly.

<h1>get your own api key and login, please</h1>

CSS

body {
    font-family: arial;
    font-size: 12px;
    line-height: 1.5;
}
a {
    padding: 2px;
    text-decoration: none;
    color: blue;
}
a.shortened:hover, a:hover {
    background: none;
    color: blue;
}

a.shortened {
    background: green;
    color: yellow;
}
h1 {
    font-size: 22px;
    font-weight: 700;
}
a span {
    background: cyan;
    margin-left: 10px;
}

JavaScript

Request.bitly = new Class({
    // return json data with extended information of a place / location.
    Extends: Request.JSONP,
    options: {
        log: !true,
        bitly: {
            api: "R_e744c730bdde44a7eacc88cb892074e7",
            login: "webtogs2"
        },
        url: "http://api.bit.ly/v3/shorten?login={login}&apiKey={api}&longUrl={longUrl}&format=json"
    },
    initialize: function(loc, options) {
        this.parent(options);
        this.options.bitly.longUrl = loc;
        this.options.url = this.options.url.substitute(this.options.bitly);
    },
    success: function(data, script) {
        this.parent(data, script);
    }
});


document.getElements("a").each(function(el) {
    new Request.bitly(el.get("href"), {
        onSuccess: function(data) {
            if (data && data.data && data.status_code == 200) {
                var orig = data.data.long_url, hash = data.data.url, difference = orig.length - hash.length;
                
                if (difference > 0) {
                    el.set({
                        href: hash,
                        title: hash + " - saved " + difference + " chars"
                    }).addClass("shortened");
                }
                else {
                    var error = "<span>ERROR:\n your bit.ly hash '" + hash + "' is longer than the original '" + orig + "'</span>";
                    el.set("html", el.get("html") + error);
                }
            }
        }
    }).send();

});