Html Country List with flags

Just wanted to suggest a (imho) smarter way of doing the flags sprite.

The idea is to save the flags in a grid according to the country iso2 code.

1st letter -> vertical position
2nd letter -> horizontal position

Examples (for 16x11px flags + 4x4px spacing):

Austria = AT
A = 1   => vertically 1st row       => y = (1-1)*(11+4)  = 0
T = 20  => horizontally 20th column => x = (20-1)*(16+4) = 380

United States = US
U = 21  => vertically 21st row      => y = (21-1)*(11+4) = 300
S = 19  => horizontally 19th column => x = (19-1)*(16+4) = 360

This way I can calculate the flag location with a very easy function on the client side without the need of 200+ extra style definitions.

Sample jQuery plugin:

(function($) {
    // size = flag size + spacing
    var default_size = {
        w: 20,
        h: 15
    };

    function calcPos(letter, size) {
        return -(letter.toLowerCase().charCodeAt(0) - 97) * size;
    }

    $.fn.setFlagPosition = function(iso, size) {
        size || (size = default_size);

        return $(this).css('background-position',
            [calcPos(iso[1], size.w), 'px ', calcPos(iso[0], size.h), 'px'].join(''));
    };
})(jQuery);

Demo Usage:

$('.country i').setFlagPosition('es');

http://jsfiddle.net/roberkules/TxAhb/

And here my flag sprite:

enter image description here


Note from the future: jQuery UI autocomplete now supports custom rendering by default, see http://api.jqueryui.com/autocomplete/#method-_renderItem.

It's pretty easy. Things you need:

  1. jQuery UI auto-complete
  2. UI auto-complete html extension
  3. A list of country names/codes
  4. A CSS sprite with all flags

Remember, Google is your friend. Blend the ingredients well, carefully whisk some javascript in, and it's done - in 7 lines of code:

var countries = [["Argentina", "ar"], ...];

var countryNames = countries.map(function(country){
  return {
      label: '<div class="flag '+country[1].toLowerCase()+'">'+country[0]+'</div>',
      value: country[0]
  }
});

$('#country').autocomplete({
  source: countryNames,
  html: true
});

Here's this code in action