Charl van Niekerk » Blog

Main

Latest

Archives

Powered by Blogger

TinyLink, Ajaxified!

I made use of TinyLink's JSON API.

I put the following links at the bottom of my posts:

<p class="post-tinylink"><a href="http://tinylink.co.za/create.php?url=http://blog.charlvn.za.net/2007/10/tinylink-api-consumer-php-shell-script.html">Get TinyLink</a></p>

The url parameter is basically just the permalink to the post.

Then I call the following JavaScript after all the links have been loaded:

var tinylink = Array();
var tinylinkA = document.getElementsByTagName("a");
var tinylinkExpected = 0;
function tinylinkDisplay() {
  tinylink.forEach(function(element, index) {
    if (element != null) {
      var textnode = document.createTextNode(" " + element["url"]);
      tinylinkA[index].parentNode.insertBefore(textnode, tinylinkA[index].nextSibling);
      tinylinkExpected--;
      tinylink[index] = null;
    }
  });
  if (tinylinkExpected > 0) {
    window.setTimeout(tinylinkDisplay, 200);
  }
}
function tinylinkFetch(event, count) {
  event.currentTarget.removeEventListener("click", tinylinkFetch, false);
  event.preventDefault();
  var href = event.currentTarget.href.replace("create.php", "api/json.php");
  var i = 0;
  while (i < tinylinkA.length && tinylinkA[i] != event.currentTarget) i++;
  href += "&name=tinylink[" + i + "]";
  var script = document.createElement("script");
  script.setAttribute("type", "application/javascript");
  script.setAttribute("src", href);
  document.getElementsByTagName("body")[0].appendChild(script);
  tinylinkExpected++;
  tinylinkDisplay();
}
for (var i = 0; i < tinylinkA.length; i++) {
  if (tinylinkA[i].href.indexOf("http://tinylink.co.za/create.php?url=") == 0) {
    tinylinkA[i].addEventListener("click", tinylinkFetch, false);
  }
}

Ok, I realise this still needs a lot of work, but at least it functions in Gecko. What needs to be done:

This script is built on the concept of "ideal" semantics where the content and behaviour is totally separated. This is also a good example of graceful degradation.

Anyway, now I go to bed. Expect improvements to this script to be published sometime into the future whenever I get time (not like I really had time now but anyway).

0 Comments

Post a Comment

Copyright © 2004-2009 Charl van Niekerk. All articles are released under the Creative Commons Attribution 2.5 South Africa licence, unless where otherwise stated.