javascriptjquerythis

Need help in my jquery plugin


Last week a made a function for ellipsing the text inside some selector.

I was calling the function like this:

ellipsiText('.class',50) passing the selector and the max length of the text that i wanted to. This works fine, but im trying to make it a plugin, to call like this: $('.class').ellipsiText(50).

So, i was reading the tutorial in jquery website, and i understood how to do it. But i think i'm having an issue with the "this" seletor. Here is my original function:

function ellipsiText(selector,maxLength){


    var array = $(selector).map(function(){
        return $(this).text();
    }).get();

    var i;

    var teste = [];

    for (i=0;i<array.length;i++){

        if (array[i].length > maxLength){

        teste.push(array[i].substr(0,maxLength) + "...");

        } else {

            teste.push(array[i]);
        }
    }

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

    $(selector).each(function(i){

        $(this).text(teste[i]);

    });

    }


}

and here is my tentative of making a jquery plugin:

(function ($) {

    $.fn.ellipsiText = function(length){

        var array = $(this).map(function(){
            return $(this).text();
            }).get();

        var i;
        var teste = [];

        for (i = 0; i < array.length; i++){
            if (array[i] > length){
                teste.push(array[i].substr(0,length) + "...");
            } else {
                teste.push(array[i]);
            }
        }

        $(this).each(function(i){

            $(this).text(teste[i]);

        }); 
    };

}(jQuery));

What am i doing wrong?


Solution

  • This is untested, but the basic structure is something like this. Also you have so much looping in your code when one loop is needed.

    $.fn.ellipsiText= function(options) {
    
        var settings = $.extend({  //nice way to give to give defaults
            length : 50,
            ellipsi : "..."
            }, options );
    
        return this.each(function() {  //the return is needed for chaining
            var elem = $(this);
            var txt = elem.text();
            if (txt.length>settings.length) {
                 elem.text(txt.substr(0,settings.length) + settings.ellipsi );
            }
        });
    
    };
    

    and call it

    $( "div.defaults" ).ellipsiText();
    
    $( "div.foo" ).ellipsiText({
        length : 10
    });
    
    $( "div.more" ).ellipsiText({
        length : 10,
        ellipsi : "<more>"    
    });