JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://github.com/dandean/Ajax.JSONRequest/raw/master/jsonp.js"></script>
<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://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
// set up default options
var defaults = {
login: "pacoguzman",
apiKey: "R_82a79a9f00b850a5e86cdf60c5791a65",
longUrl: ""
};
// Build the URL to query
$$("a").each(function(el) {
var url = "http://api.bit.ly/v3/shorten";
var longUrl = el.readAttribute("href");
new Ajax.JSONRequest(url, {
/*callbackParamName: "jsoncallback",*/
parameters: {
longUrl: longUrl,
login: defaults.login,
apiKey: defaults.apiKey,
format: "json"
},
onCreate: function(response) {
console.log("1: create", response, response.responseJSON);
},
onSuccess: function(response) {
console.log("1: success", response, response.responseJSON);
var data = response.responseJSON;
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.writeAttribute("href", hash);
el.writeAttribute("title", hash + " - saved " + difference + " chars");
el.addClassName("shortened");
}
else {
var error = "<span>ERROR:\n your bit.ly hash '" + hash + "' is longer than the original '" + orig + "'</span>";
el.insert(error);
}
}
},
onFailure: function(response) {
alert(response);
console.log("1: fail", response, response.responseJSON);
},
onComplete: function(response) {
console.log("1: complete", response, response.responseJSON);
}
});
});