1. James Robert
  2. jQuery UrlShortener

Wiki

Clone wiki

jQuery UrlShortener / Home

Install

Download the jquery.urlshortener.js file and add it to your html page after you load jquery

<script type='text/javascript' src='/path/to/jquery.js'></script>
<script type='text/javascript' src='/path/to/jquery.urlshortener.js'></script>

Usage

You need to set up your bitly account before they will allow you to access their api once you have an account and you find your api key set that up first

$.shortenUrl.settings.login = 'YOUR_BITLY_USERNAME';
$.shortenUrl.settings.apiKey = 'YOUR_API_KEY';

You only need to set the api settings once in your page, just make sure you do it before you try to shorten any Urls.

Shortening a url is easy, just make a call like this anywhere after you set your api settings:

var longUrl = 'http://www.example.com/a-really-long-url/at-least/too-long-for-twitter/';
$.shortenUrl(longUrl, function(short_url) {
    // do whatever you want with the shortened url here
});

The reason we have a callback function is because we have to do some ajax to get the short url ;)

Note: Shortened URL's are cached, so doing something like this will only hit the API once:

function function_that_uses_url_shortener() {
    var longUrl = 'http://www.example.com/a-really-long-url/at-least/too-long-for-twitter/';
    $.shortenUrl(longUrl, function(short_url) {
        // do whatever you want with the shortened url here
    });
}

function_that_uses_url_shortener();
function_that_uses_url_shortener();
function_that_uses_url_shortener();
function_that_uses_url_shortener();

Updated