On 11/17/06, Roberto Ortelli <[EMAIL PROTECTED]> wrote:
> Hello,
> A few weeks ago I've written a small plugin for that:
>
> $.fn.fieldFocus = function(id){
>         document.getElementById(id).focus();
> }
>
> and you call it using:
> $(document).fieldFocus("the_id_of_the_input_field_without_#");

It is great to write plugins that make your development (and hopefully
others too) faster and easier. I would just like to point out a few
things that could make your plugin a little more robust.

First a plugin's 'this' points to the jQuery object. With that in mind
you can simply write the above plugin like this:

jQuery.fn.fieldFocus = function() {
    this.get(0).focus();
};

And if you wanted to be able to chain method together you would do it like this:

jQuery.fn.fieldFocus = function() {
    this.get(0).focus();
    return this;
};

Or you could call focus on each of the elements in the jQuery object like this:

jQuery.fn.fieldFocus = function() {
    return this.each(function() {
        if (this.focus) this.focus();
    });
};

Inside of the each method the 'this' points to the actual DOM element
and not the jQuery object. I check for focus first so as not to cause
an error on elements that don't have the method.

Hope that helps.

--
Brandon Aaron

_______________________________________________
jQuery mailing list
discuss@jquery.com
http://jquery.com/discuss/

Reply via email to