Creating a Jquery Plugin

by OMR 14. November 2009 04:56

This article contains plugin based coding tecniques for jquery. Lets coding.

We are declaring plugin functions to jquery prototype.

jQuery.fn.MyAlert = function(message)
{
        alert("Attention: " + message;      
}

This code is usable pluging declaretion but not supported tecnique for cross library safety. Example of cross library supported declaretion:


(function($) {
    $.fn.MyMask = function() {
        $(this).val("Masked input element");
    }
})(jQuery);

Examle using:
$("#input1").MyMask();

Finished first runable plugin. Plugin adding "Masked input element" to input1 element. This function is only available for an element. Selective parameter may apply to multiple elements. Be applied to all elements according to the selector parameter. Therefore we should use each function.




(function($) {
    $.fn.MyMask = function() {
        this.each(function() {
            $(this).val("I am one of the masking field");
        });
    }
})(jQuery);

Now, we are develop functionatly plugin. This plug-in should check the user input. Parameter and set consisting of selectors should take two parameters. Settings parameter such as character spacing can be used to assign variables.


(function($) {
    $.fn.MyMask = function(options) {

        var defaults = {
            match: '^[0-9]+$',
            errorClass: 'MyMaskError'
        };

        var mySettings = $.extend({}, defaults, options);

        this.each(function() {
            $(this).keypress(function(e) {
                /*
                var kk = e.which;
                if (kk != 16 && kk != 32 && kk < 41) return true;
                */

                CheckIt($(this), String.fromCharCode(e.which));
            });

            $(this).blur(function() {
                CheckIt($(this), 0);
            });
        });

        function CheckIt(s, newChar) {
            if (!new RegExp(mySettings.match).test(s.val() + newChar))
            { s.addClass(mySettings.errorClass); }
            else
            { s.removeClass(mySettings.errorClass); }
        }
    }
})(jQuery);

This code snippet into the text box is checked the match of the data was entered. Regular expression with expression data entered does not match the assignment makes MyMaskError css. We wrote our first jQuery plugin. Sweet dreams.

Resources:

jquery.mymask.v0.1b.js (909,00 bytes)
MyMask.htm (595,00 bytes)

Tags:

english | jquery

Comments

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
Loading



Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen