Zip That! A Simple Client-Side URL Shortener Script Calling the Bit.ly API


Zip That URL!

This domain is for sale!

Please try the above tiny URL shortener – it is driven by a small piece of javascript calling the Bit.ly API, which can easily be integrated into any webpage, e.g. like so:

<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function()
{
  function bit_url(url) 
  { 
    var token="8e25559b640124c0d2800f83ee37f82f6802f0d6";
    $.ajax({
      url:"https://api-ssl.bitly.com/v3/shorten",
      data:{longUrl:url,access_token:token},
      dataType:"jsonp",
      success:function(v)
      {
        var bit_url=v.data.url;
        $("#result").html('<a href="'+bit_url+'"target="_blank">'+bit_url+'</a>');
      }
    });
  }
  $("#short").click(function()
  {
    var url=$("#url").val();
    var urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&#038;@#\/%?=~_|!:,.;]*[-A-Z0-9+&#038;@#\/%=~_|])/ig;
    var urltest=urlRegex.test(url);
    if(urltest)
    {
      bit_url(url);
    } else {
      alert("Bad URL");
    }
  });
});
</script>
<style type="text/css">
#wrapper {
  width: 240px;
  margin: 0 auto;
}
#url {
  width: 140px;
  border: solid 3px #caa800; 
  padding: 4px; 
  font-size: 15px
}
#short {
  width: 70px;
  border: solid 3px #883414; 
  padding: 4px; 
  font-size: 15px;
}
@media(min-width:400px) { 
  #wrapper {
    width: 350px;
  }
  #url {
    width: 250px;
  }
  #short {
    width: 80px;
  }
}
</style>
<div align="center">
  <h1>Zip That URL!</h1>
</div>
 
<div id="wrapper" align="center">
  <div style="float:left;">
    <input id="url" name="url" type="text" value="http://" />
  </div>
  <div style="float:left;">
    <input id="short" type="submit" value="Zip That!" />
  </div>
  <div style="clear:both;">&nbsp;</div>
  <div id="result" style="width: 200px; margin: 0 auto;"></div>
</div>
</body>
</html>

Of course you can also setup your own branded short domain with bit.ly, and adapt the text accordingly. In this case you will also need to create your own generic access_token for the OAuth-based authentication: to do this, visit this page when logged in at bit.ly. Once you created the token, simply replace the token used in line 16 of the above code with your own one, and all is set and done!

If you visited this page while reading our series of short articles on setting up your own URL shortener, you might want to return to Part 2.