google+javascriptbanktwitter@js_bankfacebook@jsbankrss@jsbank






Reuse JavaScript codes as jQuery Plugins: Tutorials and Examples The other purpose of this JavaScript article tutorial is it to guide us step by step to build a plug-in for jQuery framework by reusing old JavaScript source codes or you can write new ones. From this JavaScript article tutorial, you will learn how to create a completed jQuery plug-in, please go to the inner post page for full instructions, comments and JavaScript code examples.


Label: Reuse JavaScript codes, build jQuery Plugin, step by step, old JavaScript source code

Free iPage Web Hosting for First Year NOW



If you're still looking for a reliable web host provider with affordable rates, why you don't take a little of time to try iPage, only with $1.89/month, included $500+ Free Extra Credits for the payment of 24 months ($45)?

Over 1,000,000+ existisng customers can not be wrong, definitely you're not, too! More important, when you register the web hosting at iPage through our link, we're going to be happy for resending a full refund to you. That's awesome! You should try iPage web hosting for FREE now! And contact us for anything you need to know about iPage.
Try iPage for FREE First Year NOW

Our team finds that we get the greatest leverage out of our existing collection of code snippets by organizing them into well structured, easy to maintain libraries of pluggable modules. This is the first article in a two part series. In this article, we take a whirl-wind tour of how to create reusable modules with front-end JavaScript code using the popular jQuery library. In my follow-up article, we will briefly examine the Web Storage technology that has come out of the HTML5 specification process and then show how simple it is to wrap it within a jQuery plugin.

If you go back and look through the last few web app projects you’ve completed, you probably will find that you have accumulated a variety of snippets of JavaScript that may have even been tweaked to be reused in follow-on projects. If you haven’t yet organized these bits of code in a particular way, you may want to consider leveraging an existing framework that provides well-defined structure for code reuse.

Our team primarily uses jQuery, a very straightforward and easy to use JavaScript library originally created by John Resig back in 2006. If you are new to jQuery, we recommend the excellent jQuery in Action book and jQuery’s own website for pointers to tutorials and documentation.

jQuery has two logical components. The base jQuery library includes a powerful CSS-like selector mechanism, easy methods to manipulate the DOM, rich effects, Ajax support, utilities, and more. The jQuery UI library provides a collection of user interface widgets. These two parts of jQuery form the basis of a rich ecosystem that is further enhanced with many plugins. Writing jQuery plugins is pretty straight-forward once you are familiar with the basic conventions.

Conventions Conventions

If jQuery is a fit for your project, you can utilize its conventions to reap the benefits of a consistent code style, logical approach to working with data, and to easily leverage other basic building blocks of code.

Three particular best practices are self-evident with a quick review of the jQuery community (see the plugin authoring guidelines for more details).

First, files, functions, data, and events should follow naming rules to help form and maintain namespaces. Files will typically use the pattern of “jquery-prefix-name-version.js”. “jquery” identifies the file as a jQuery compatible piece of code, often a plugin. “prefix” is an optional word, acronym, or hyphenated phrase that identifies an organization or group of related files. “name” is the name of the plugin. “version” is usually the major and minor version numbers of the code, e.g. jquery-webvanta-icon-picker-1.0.js.

Functions, data, and events should use specific techniques outlined in the jQuery Plugin Authoring guidelines to minimize conflicts between different plugins.

A second convention deals with the common issue of protecting your jQuery plugin from interference by other JavaScript libraries or function namespaces. It also typically includes a simple trick for safely accessing the shorthand “$” variable which holds a reference to the jQuery object. By defining a self executing anonymous function that forms a closure, you keep your code reasonably isolated:

  (function($){
    $.iconPicker = function() {

      // Your code goes here
    }
  })(jQuery);

The anonymous function runs as soon as it is defined, passing the global “jQuery” value as a parameter, where it gets assigned to the local parameter name “$”, which is then accessible to the internal scope of the function regardless of what “$” may be outside.

A third convention details how parameters are passed to your plugin. Rather than long and complicated function signatures with many individual parameters (e.g. icon-picker(element, color, size, effect, delay)), utilize the technique of passing in a single JavaScript literal object, which simulates a collection of name/value pairs. This makes for more readable code, and makes it easy to implement default values and to allow for arbitrary missing or added parameters:

  $.iconPicker({element: el, color: 'blue', size: 3, effect: 'shrink', delay: 1000});

You’ll use this technique most commonly when writing a plugin with many optional parameters. For Rubyists, this may look similar to using a tailing hash in the parameter list to pick up arbitrary or named parameters.

Plain Old Utility Function Pattern

Utility functions are typically small routines that accomplish some basic self-contained task, such as string or date-time manipulation, working with cookies, or logging information. In the jQuery world, the usual approach to organizing such code is to attach these functions off of the main jQuery namespace. Remembering our conventions discussed earlier, this might look like:

(function($){
  $.webvantaUtils = {};

  $.webvantaUtils.readCookie = function(name) {
      var ne = name + "=",

      ca = document.cookie.split(';');
      for(var i=0;i < ca.length;i++) {

        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);

        if (c.indexOf(ne) == 0) return c.substring(ne.length,c.length);

      }
      return null;
    }
})(jQuery);

Note we have namespaced our cookie related function under a higher level namespace organized in this case by a company library.

Once defined, you can use such a function elsewhere via simple reference (you could use “$” rather than jQuery if you wish and you know that it isn’t being used for some conflicting purpose in the scope of the call):

var myUser = jQuery.webvantaUtils.readCookie('user_info');

Wrapped Set Function Pattern

If you have utilities that act on DOM elements, you should tie in to jQuery’s ability to operate on a collection of DOM elements called a wrapped set.

Instead of assigning our functions to the top-level jQuery namespace, we instead connect to the “fn” object, which gains us access to the wrapped set through the “this” variable.

Let’s say you have some utility code that counts how many times any of your form input elements contain a particular letter sequence:

(function($){
  $.fn.redAlert = function(badValue) {

    var badValueFound = 0;
    this.each(function() {
      if ($(this).val().toLowerCase().indexOf(badValue.toLowerCase()) >= 0)

        badValueFound = badValueFound + 1;
    });
    return badValueFound;

  };
})(jQuery);

We use the wrapped set found in the first “this” and call an iterator on it to walk through each value in the set. Within the function passed to the “each” iterator, the value of “this” changes to point to one of the wrapped set’s DOM elements. We can reconstitute that element as a jQuery object with the $(this) idiom, and use it as we wish…here to compare some string values.

You might use the plugin like so:

  if ($("form input:text").redAlert('Stink') > 0)
    alert("Something smells in the form");

In this contrived example, we are returning an integer value to accomplish our goals.

AIVideo-App.com
Generate your business videos by AI with voice or just text

chatGPTaz.com
Talk to ChatGPT by your mother language

AppAIVideo
Your first FREE AI Video App

Deepfake Video
Deepfake AI Video Maker

Deepfake
Deepfake AI Video Maker

AI Deep Fake
Deepfake AI Video Maker

AIvidio
AI Video Mobile Solutions

AIvideos
AI Video Platform & Solutions

AIvedio
AI Video App Maker

Faceswap AI Online
Swap Faces Video, Photo & GIFs Instantly with Powerful AI Tools - Faceswap AI Online FREE

Faceswap AI Online
Swap Faces Video, Photo & GIFs Instantly with Powerful AI Tools - Faceswap AI Online FREE

Temu Free $500 for New Users
Claim Free Temu $500 Credit via Affiliate & Influencer Program

Free TikTok Ads Credit
Master TikTok Ads for Your Business Marketing

Dall-E-OpenAI.com
Generate creative images automatically with AI

chatGPT4.win
Talk to ChatGPT by your mother language

First AI Product from Elon Musk - Grok/UN.com
Speak to Grok AI Chatbot with Your Language

Tooly.win
Open tool hub for free to use by any one for every one with hundreds of tools

GateIO.gomymobi.com
Free Airdrops to Claim, Share Up to $150,000 per Project

iPhoneKer.com
Save up to 630$ when buy new iPhone 16

Buy Tesla Optimus Robot
Order Your Tesla Bot: Optimus Gen 2 Robot Today for less than $20k

JavaScript by day


Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web