regan
regan

Reputation: 405

How do I make this jQuery plugin chainable?

Can anyone show me how to go about making this jQuery plugin chainable? The plugin limits text input into a field, and returns a remaining text count to the 2nd argument if passed in. Thanks.

(function($) {

$.fn.extend({
    limit: function(limit, element) {
        var interval;
        var self=$(this);
        $(this).focus(function(){
            interval = window.setInterval(function(){
                substring(self, limit, element);
            },100)
        });
        $(this).blur(function(){
            clearInterval(interval);
            substring(self, limit, element);
        });
        substring(self, limit, element);
    }
});

function substring(self, limit, element) {
    var val = $(self).val();
    var length = val ? val.length : 0 ;
    if( length > limit ) {
        $(self).val($(self).val().substring(0,limit));
    }
    var toe = typeof element;
    if (toe!='undefined') {
        if (toe=='string') {
            $(element).html((limit-length<=0)?'0':limit-length);
        } else if (toe=='object') {
            element.html((limit-length<=0)?'0':limit-length);
        }
    }
}

})(jQuery);

Upvotes: 1

Views: 955

Answers (3)

nav
nav

Reputation: 3115

I would go a step further and allow this to work on an array of jQuery elements by using the each() function:

$.fn.extend({
    limit: function(limit, element) {
        return this.each(function() {
            var self=$(this);
            $(this).focus(function(){
                interval = window.setInterval(function(){
                    substring(self, limit, element);
                },100)
            });
            $(this).blur(function(){
                clearInterval(interval);
                substring(self, limit, element);
            });
            substring(self, limit, element);
        });
    }
});

Also see http://docs.jquery.com/Plugins/Authoring#Maintaining_Chainability for more information regarding the authoring of jQuery plugins.

Upvotes: 2

Daff
Daff

Reputation: 44215

Always return this at the end of a plugin method (which is also the expected behaviour and should always be done unless there is a good and well documented reason):

$.fn.extend({
    limit: function(limit, element) {
        var interval;
        var self=$(this);
        $(this).focus(function(){
            interval = window.setInterval(function(){
                substring(self, limit, element);
            },100)
        });
        $(this).blur(function(){
            clearInterval(interval);
            substring(self, limit, element);
        });
        substring(self, limit, element);
        return this;
    }
});

Upvotes: 2

SLaks
SLaks

Reputation: 887449

Just return this; at the end of the method.

Upvotes: 5

Related Questions