Auto Shorten dynamic URL by javascript

Live Demo

Thinking of using Url Shortening service in your site? You can use a simple javascript code in any page of your site, specially if it is a dynamic page. For example, look at a dynamic page of my online code compiling site:

The link of a dynamic page is somewhat this:

The link is too long. So, I automatically shortened the links, and gifted it to the viewers!😉

how to use in your site

How to use service in your site

First, you need an account on To create one, go to the site and register.

Once you’ve registered, login and go to your Account page. There, you will find your API key.

Now, we’ve all the resources. Let’s go to the code section

The Code

Between the <HEAD> and </HEAD> tag of your page, place the following code:

  • <script type="text/javascript" charset="utf-8" src="******&apiKey=*****************"></script>
  • Replace the first ***** by your username and second ************** by your API key!

    Now, place the following code anywhere of your page. It is nothing but a text-input field, where shortened link will be placed. You can use anything instead of a text area, perhaps a <div>tag to display the shortened link!

    <h3>Link to this page</h3><br>
    Use this link to tell others about this page! <input onclick = "" type = 'text' id = "qlink" style = "width:100%;">

    Now, the final task. Place the following code just before </BODY> the tag of you page:

    	// API
    	BitlyCB.shortenResponse = function(data) {
    			var sss = '';
    			var first_result;
    			// Results are keyed by longUrl, so we need to grab the first one.
    			for     (var r in data.results) {
    					first_result = data.results[r]; break;
    			sss = first_result["shortUrl"].toString();
    			document.getElementById("qlink").value = sss;
    	BitlyClient.shorten(window.location, 'BitlyCB.shortenResponse');

    Yeah, you’re done! Now anyone entering the page with any query string, the link of the page with the query string will be automatically shortened😀

    4 thoughts on “Auto Shorten dynamic URL by javascript

    1. Nice Article,

      Is this only for one URL or we can use multiple, if we want multiple then do we have to code like this for each URL?


    Leave a Reply

    Fill in your details below or click an icon to log in: Logo

    You are commenting using your account. Log Out / Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out / Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out / Change )

    Google+ photo

    You are commenting using your Google+ account. Log Out / Change )

    Connecting to %s