Html Country List with flags

Mr.B picture Mr.B · Mar 23, 2011 · Viewed 71.7k times · Source

I am looking for a way to select and display a list of countries, preferably with flags. Any suggestions?

I started of by trying this jQuery plugin http://www.graphicpush.com/website-language-dropdown-with-jquery, but as the list of countries I have is quite large it turned out that the performance was really bad (too many http requests to images). Also the list is bulky when it is larger than 50 elements.

Answer

roberkules picture roberkules · Jun 20, 2012

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