jQuery: creare un plugin per generare una tag cloud

Come sviluppare un plugin jQuery per generare una tag cloud.

jQuery di Gabriele Romanato

Creare un plugin jQuery per generare una tag cloud richiede semplicemente la gestione di tre parametri: l'URL dei link, la dimensione del font e il testo da visualizzare. Una volta ottenuti questi parametri, il nostro plugin è pronto per l'uso. Vediamo come procedere.

Useremo come unica opzione del nostro plugin un array multidimensionale in cui ciascun array membro contiene i tre parametri sopra indicati:


(function($) {

    $.fn.tagcloud = function(options) {

        var that = this;
        var settings = {
            items: []
        };

        options = $.extend(settings, options);

        return that.each(function() {

            var html = '';

            for (var i = 0; i < options.items.length; i++) {

                var opts = options.items[i];
                html += '<a href="' + opts[0] + '" style="font-size: ' + opts[1] + 'px">' + opts[2] + '</a>';

            }

            $(that).html(html);

        });

    };


})(jQuery);

Ecco un esempio d'uso:


$('#tag-cloud').tagcloud({
    items: [
        ['#', '10', 'CSS'],
        ['#', '16', 'XHTML'],
        ['#', '22', 'jQuery'],
        ['#', '38', 'JavaScript'],
        ['#', '14', 'SVG'],
        ['#', '50', 'PHP'],
            ['#', '13', 'HTML5']
        ]
});​

Potete visionare l'esempio finale in questa pagina.