What is the best practice of including jQuery ext functions?

I currently have a file that I named JQuery.ext.js, which I include in all of my pages. Inside this file, I have many functions that perform the following actions:

(function($) {


    /**
     * Checks to see if a container is empty. Returns true if it is empty
     * @return bool
     */
    $.fn.isEmptyContainer = function() {
        //If there are no children inside the element then it is empty
        return ($(this).children().length <= 0) ? $(this) : false;
    };

    /**
     * Strip html tags from elements
     * @return jQuery
     */
    $.fn.stripHTML = function() {
        var regexp = /<("[^"]*"|'[^']*'|[^'">])*>/gi;

        //Loop through all elements that were passed in
        this.each(function() {
            $(this).html($(this).html().replace(regexp, ""));
        });
        return $(this);
    };

    /**
     * This function will check the length of a textarea and not allow the user to go beyond this length.
     * You should use the onkeypress event to trigger this function
     *
     * @param event event This value should always be event when passing it into this function
     * @param maxlength int The maximum amount of character that the user is allowed to type in a textarea
     */
    $.fn.enforceMaxLength = function(event, maxlength) {
        //Only allow the client code to use the onkeypress event
        if(event.type == 'keypress') {
            //If the client code does not pass in a maxlength then set a default value of 255
            var charMax = (!maxlength || typeof(maxlength) != "number") ? 255 : maxlength;

            //If the user is using the backspace character then allow it always
            if(event.which == 8) { return true; }
            //Else enforce the length
            else { return ($(this).val().length <= charMax); }
        }

        //Will only get here if the event type is not keypress
        return false;
    };
})(jQuery);

Is there any other way to do this? or is it like most people do?

Thanks for any help, Metropolis

EDITED

Added different plugins for the code and removed verification plugins

+3
source share
2 answers

It all depends on the volume of these functions. If you have a list of very common functions that you constantly use in your applications, I would put them in a separate file and include them if necessary.

: , , , . , .:)

, , , , , . , - jquery-validate $.validator.addMethod().

Edit

, / jQuery, , :

(function ($) {
   // my list of functions, plug-ins, or classes; as needed by the application
}(jQuery);

. : , /, 3 : jquery.myvalidation.js, jquery.myformatting.js .. , , , , "" jQuery ( ) ( ).

, , - , . jQuery, (, , scrollTo ).

+2

. , .

0

Source: https://habr.com/ru/post/1745489/


All Articles