Christian Heilmann

Posts Tagged ‘jquery’

Building with JavaScript – write less by using the right tools

Wednesday, September 1st, 2010

Yesterday Framsia organized a meetup in Oslo, Norway with Molly Holzschlag, Paul Irish and me ramping up to the Frontend2010 conference. Molly talked about the open web and the open stack of technologies and Paul showed people the developer tools in Chrome.

My talk was about building web applications with JavaScript and how using progressive enhancement helps you build great things with very few lines of code. The slides are available on Slideshare:

As per usual, I also created a audio recording of the talk hosted on The Internet Archive:

I loved the evening – the location sponsored by Epinova had all the things we needed (including a copious amount of beer) and the audience (once warmed up) had some very good questions to answer. The talks were filmed and Framsia will release them soon.

Worldinfo – my Event Apart 10KB submission (information and documented source code)

Tuesday, August 17th, 2010

As you might know, an Event Apart in association with Microsoft are currently running a competition asking developers what they can do in under 10KB and I thought I have a shot at that.

So here’s my submission: an interface to get information about any country on this planet in under 5K:

I got the idea last Thursday during Pub Standards in London when someone asked me if it is possible to get information about all the countries in the world using YQL. The main interest was not only to get the names but also the bounding box information in order to display maps with the right zoom level. And it is, all you need to do in YQL is the following:

select name,boundingBox from geo.places.children(0) where
parent_woeid=1 and placetype=”country” | sort(field=”name”)

This gets all the children of the entry with the WOEID of 1 (Earth, that is) in the GeoPlanet dataset that are a country and sorts them alphabetically for you.

Each of the results comes with bounding box information which you then can use to display a map with the Open Streetmap static image API (or any other provider). For example:

http://pafciu17.dev.openstreetmap.org/?
module=map&bbox=38.804001,37.378052,
48.575699,29.103001&width=500&height=250

Or as I use it:

var image = ‘http://pafciu17.dev.openstreetmap.org/?module=map&bbox=’+
bb.boundingBox.southWest.longitude+’,’+
bb.boundingBox.northEast.latitude+’,’+
bb.boundingBox.northEast.longitude+’,’+
bb.boundingBox.southWest.latitude+
‘&width=500&height=250’;

The last piece to the puzzle was where to get country information from and of course the easiest is Wikipedia. Every country web site in Wikipedia has a info table about it which turned out to be too much of a pain to clean up so all I did was to scrape the first three paragraphs following this table with YQL:

select * from html where
url=”http://en.wikipedia.org/wiki/Christmas_Islands”
and xpath=”//table/following-sibling::p” limit 3

The rest, as they say, is history. I built the system in all in all 2 hours and now I spent some time to clean it up and spice it up:

World Info - my 10kb app compo entry (spiced up source version) by photo

As the first loading of the data takes a long time I use HTML5 local storage to cache the country information. This means you only have to wait once and subsequently it’ll be much faster.

You can download and see the source of Worldinfo on GitHub and read through the massive amount of comments I left for you.

If I were to build this as a real product I would cache the results on a server rather than hammering the APIs every time a user comes along – as the information doesn’t change much this makes much more sense. I will probably release a PHP version of that soon. For now, this is what we have.

Rotating maps with CSS3 and jQuery

Tuesday, February 9th, 2010

One thing that annoys the heck out of me with maps you see on a screen is that you can’t rotate them. When I look at a real map I constantly turn it around so that I face in the right direction. Google maps lately added this feature in the hybrid and satellite maps but I wanted to do that with the simple maps and also other map providers.

The solution was CSS3. With the rotation transformations you can arbitarily turn elements. Of course this differs again from browser to browser which is why it made sense to me to find a library plugin that does that. Zachary Johnson build one of those and using this together with the Google Maps API it was pretty easy to build a rotating map:

Rotating a map with CSS3 and jQuery by  you.

The code itself is very easy – thanks to the transformation work already done in Zach’s code:

google.load("maps", "2.x");
   function initialize() {
     var mapcontainer = $('#mapcontainer');
     var mapdiv = $('#map');
     var geocoder = new GClientGeocoder();
     var map = new google.maps.Map2(mapdiv);
     map.addControl(new GSmallMapControl());
     map.addControl(new GMapTypeControl());
     map.setCenter(new google.maps.LatLng(37.4419, -122.1419), 13);
     mapcontainer.after('<div id="buttons">'+
                        '<form id="f"><label for="loc">Location:</label>'+
                        '<input type="text" id="loc">'+
                        '<input type="submit" value="go"></form>'+
                        '<p>Press R and L to rotate map, = to reset.</p>'+
                        '<p>Use cursor keys to move.</p>'+
                        '<p>Zoom with + and -.</p>'+
                        '</div>');
     mapcontainer.attr('tabIndex','-1');
     mapcontainer.focus();
     $('#f').submit(function(event){
       var value = $('#loc').attr('value');
       if (geocoder) {
          geocoder.getLatLng(
            value,
            function(point) {
              if (!point) {
                alert(value + " not found");
              } else {
                map.setCenter(point, 13);
                var marker = new GMarker(point);
                map.addOverlay(marker);
                mapcontainer.focus();
              }
            }
          );
        }
       return false;
     });
     mapcontainer.keydown(function(event){
       switch(event.keyCode){
         case 82: mapdiv.animate({rotate: '+=5deg'}, 0); break;
         case 76: mapdiv.animate({rotate: '-=5deg'}, 0); break;
         case 40: map.panDirection(0,-1); break;
         case 38: map.panDirection(0,1); break;
         case 39: map.panDirection(-1,0); break;
         case 37: map.panDirection(1,0); break;
         case 107: map.setZoom(map.getZoom()+1); break;
         case 109: map.setZoom(map.getZoom()-1); break;
         case 61: mapdiv.animate({rotate: '0'}, 0); break;
       }
     });
   }
   google.setOnLoadCallback(initialize);

Of course I was not the first with this. The StreetView Fun demo by Lim Chee Aun (@cheeaun) has a similar implementation (click “maps” in the demo to see it):

StreetView Fun by  you.

Things to fix

  • Map navigation: as you might have already experienced, dragging the map is becoming very confusing. This cannot really be solved as it would require Google Maps to know the rotation. Right now I am using the panDirection method to move the map with the cursor keys – a cleaner way would be to use PanTo and really calculate the next place to pan to taking into consideration the angle of the map. Any volunteers?
  • I am quite sure I am violating Google’s terms and conditions with this as I am cropping off the copyright.I found a way to display the copyright and Google branding:

GEvent.addListener(map, "tilesloaded", function() {
 var logo = $('#logocontrol');
 logo.attr('style','');
 var copyright = $('#map div[dir=ltr]');
 copyright.attr('style','');
 $('#mapinfo').append(logo);
 $('#mapinfo').append(copyright);
});

Loading external content with Ajax using jQuery and YQL

Sunday, January 10th, 2010

Let’s solve the problem of loading external content (on other domains) with Ajax in jQuery. All the code you see here is available on GitHub and can be seen on this demo page so no need to copy and paste!

OK, Ajax with jQuery is very easy to do – like most solutions it is a few lines:

$(document).ready(function(){
  $('.ajaxtrigger').click(function(){
    $('#target').load('ajaxcontent.html');
  });
});

Check out this simple and obtrusive Ajax demo to see what it does.

This will turn all elements with the class of ajaxtrigger into triggers to load “ajaxcontent.html” and display its contents in the element with the ID target.

This is terrible, as it most of the time means that people will use pointless links like “click me” with # as the href, but this is not the problem for today. I am working on a larger article with all the goodies about Ajax usability and accessibility.

However, to make this more re-usable we could do the following:

$(document).ready(function(){
  $('.ajaxtrigger').click(function(){
    $('#target').load($(this).attr('href'));
    return false;
  });
});

You can then use load some content to load the content and you make the whole thing re-usable.

Check out this more reusable Ajax demo to see what it does.

The issue I wanted to find a nice solution for is the one that happens when you click on the second link in the demo: loading external files fails as Ajax doesn’t allow for cross-domain loading of content. This means that see my portfolio will fail to load the Ajax content and fail silently at that. You can click the link until you are blue in the face but nothing happens. A dirty hack to avoid this is just allowing the browser to load the document if somebody really tries to load an external link.

Check out this allowing external links to be followed to see what it does.

$(document).ready(function(){
  $('.ajaxtrigger').click(function(){
    var url = $(this).attr('href');
    if(url.match('^http')){
      return true;
    } else {
      $('#target').load(url);
      return false;
    }
  });
});

Proxying with PHP

If you look around the web you will find the solution in most of the cases to be PHP proxy scripts (or any other language). Something using cURL could be for example proxy.php:

<?php
$url = $_GET['url'];
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
$output = curl_exec($ch); 
curl_close($ch);
echo $content;
?>

People then could use this with a slightly changed script (using a proxy):

$(document).ready(function(){
  $('.ajaxtrigger').click(function(){
    var url = $(this).attr('href');
    if(url.match('^http')){
      url = 'proxy.php?url=' + url;
    }
    $('#target').load(url);
    return false;
  });
});

It is also a spectacularly stupid idea to have a proxy script like that. The reason is that without filtering people can use this to load any document of your server and display it in the page (simply use firebug to rename the link to show anything on your server), they can use it to inject a mass-mailer script into your document or simply use this to redirect to any other web resource and make it look like your server was the one that sent it. It is spammer’s heaven.

Use a white-listing and filtering proxy!

So if you want to use a proxy, make sure to white-list the allowed URIs. Furthermore it is a good plan to get rid of everything but the body of the other HTML document. Another good idea is to filter out scripts. This prevents display glitches and scripts you don’t want executed on your site to get executed.

Something like this:

<?php
$url = $_GET['url'];
$allowedurls = array(
  'http://developer.yahoo.com',
  'http://icant.co.uk'
);
if(in_array($url,$allowedurls)){
  $ch = curl_init(); 
  curl_setopt($ch, CURLOPT_URL, $url); 
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
  $output = curl_exec($ch); 
  curl_close($ch);
  $content = preg_replace('/.*<body[^>]*>/msi','',$output);
  $content = preg_replace('/<\/body>.*/msi','',$content);
  $content = preg_replace('/<?\/body[^>]*>/msi','',$content);
  $content = preg_replace('/[\r|\n]+/msi','',$content);
  $content = preg_replace('/<--[\S\s]*?-->/msi','',$content);
  $content = preg_replace('/<noscript[^>]*>[\S\s]*?'.
                          '<\/noscript>/msi',
                          '',$content);
  $content = preg_replace('/<script[^>]*>[\S\s]*?<\/script>/msi',
                          '',$content);
  $content = preg_replace('/<script.*\/>/msi','',$content);
  echo $content;
} else {
  echo 'Error: URL not allowed to load here.';
}
?>

Pure JavaScript solution using YQL

But what if you have no server access or you want to stay in JavaScript? Not to worry – it can be done. YQL allows you to load any HTML document and get it back in JSON. As jQuery has a nice interface to load JSON, this can be used together to achieve what we want to.

Getting HTML from YQL is as easy as using:

select * from html where url="http://icant.co.uk"

YQL does a few things extra for us:

  • It loads the HTML document and sanitizes it
  • It runs the HTML document through HTML Tidy to remove things .NETnasty frameworks considered markup.
  • It caches the HTML for a while
  • It only returns the body content of the HTML - so no styling (other than inline styles) will get through.

As output formats you can choose XML or JSON. If you define a callback parameter for JSON you get JSON-P with all the HTML as a JavaScript Object – not fun to re-assemble:

foo({
  "query":{
  "count":"1",
  "created":"2010-01-10T07:51:43Z",
  "lang":"en-US",
  "updated":"2010-01-10T07:51:43Z",
  "uri":"http://query.yahoo[...whatever...]k%22",
  "results":{
    "body":{
      "div":{
        "id":"doc2",
        "div":[{"id":"hd",
          "h1":"icant.co.uk - everything Christian Heilmann"
        },
        {"id":"bd",
        "div":[
        {"div":[{"h2":"About this and me","
        [... and so on...]
}}}}}}}});

When you define a callback with the XML output you get a function call with the HTML data as string in an Array – much easier:

foo({
  "query":{
  "count":"1",
  "created":"2010-01-10T07:47:40Z",
  "lang":"en-US",
  "updated":"2010-01-10T07:47:40Z",
  "uri":"http://query.y[...who cares...]%22"},
  "results":[
    "<body>\n    <div id=\"doc2\">\n<div id=\"hd\">\n 
     <h1>icant.co.uk - \n
     everything Christian Heilmann<\/h1>\n 
      ... and so on ..."
  ]
});

Using jQuery’s getJSON() method and accessing the YQL endpoint this is easy to implement:

$.getJSON("http://query.yahooapis.com/v1/public/yql?"+
          "q=select%20*%20from%20html%20where%20url%3D%22"+
          encodeURIComponent(url)+
          "%22&format=xml'&callback=?",
  function(data){
    if(data.results[0]){
      var data = filterData(data.results[0]);
      container.html(data);
    } else {
      var errormsg = '<p>Error: can't load the page.</p>';
      container.html(errormsg);
    }
  }
);

Putting it all together you have a cross-domain Ajax solution with jQuery and YQL:

$(document).ready(function(){
  var container = $('#target');
  $('.ajaxtrigger').click(function(){
    doAjax($(this).attr('href'));
    return false;
  });
  function doAjax(url){
    // if it is an external URI
    if(url.match('^http')){
      // call YQL
      $.getJSON("http://query.yahooapis.com/v1/public/yql?"+
                "q=select%20*%20from%20html%20where%20url%3D%22"+
                encodeURIComponent(url)+
                "%22&format=xml'&callback=?",
        // this function gets the data from the successful 
        // JSON-P call
        function(data){
          // if there is data, filter it and render it out
          if(data.results[0]){
            var data = filterData(data.results[0]);
            container.html(data);
          // otherwise tell the world that something went wrong
          } else {
            var errormsg = '<p>Error: can't load the page.</p>';
            container.html(errormsg);
          }
        }
      );
    // if it is not an external URI, use Ajax load()
    } else {
      $('#target').load(url);
    }
  }
  // filter out some nasties
  function filterData(data){
    data = data.replace(/<?\/body[^>]*>/g,'');
    data = data.replace(/[\r|\n]+/g,'');
    data = data.replace(/<--[\S\s]*?-->/g,'');
    data = data.replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g,'');
    data = data.replace(/<script[^>]*>[\S\s]*?<\/script>/g,'');
    data = data.replace(/<script.*\/>/,'');
    return data;
  }
});

This is rough and ready of course. A real Ajax solution should also consider timeout and not found scenarios. Check out the full version with loading indicators, error handling and yellow fade for inspiration.

TTMMHTM: MOD defines Irony, Twitter translation on Yahoo, PhotoSketch, compressing Keynotes and Linux on Badgers

Tuesday, October 6th, 2009

Things that made me happy this morning: