Create simple jQuery plugin

Posted by ybbest on YBBest See other posts from YBBest or by ybbest
Published on Sun, 04 Mar 2012 03:19:16 +0000 Indexed on 2012/03/18 18:26 UTC
Read the original article Hit count: 241

Filed under:
|

In the last post, I have shown you how to add the function to jQuery. In this post, I will show you how to create plugin to achieve this.

1. You need to wrap your code in the following construct, this is because you should not use $ directly as $ is global variable, it could have clash with some other library which also use $.Basically, you can pass in jQuery object into the function, so that $ is made available inside the function. (JavaScript use function to create scope, so you can make sure $ is referred to jQuery inside the function )

(function($){   
//Your code goes here.
 };  
})(jQuery); 

2. Put your code into the construct above.
(function ($) {
    $.getParameterByName = function (name) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regexS = "[\\?&]" + name + "=([^&#]*)";
        var regex = new RegExp(regexS);
        var results = regex.exec(window.location.search);
        if (results == null)
            return "";
        else
            return decodeURIComponent(results[1].replace(/\+/g, " "));
    };
})(jQuery);  

3. Now you can reference the code into you project and you can call the method in you JavaScript

References:

Provides scope for variables

Variables are scoped at the function level in javascript. This is different to what you might be used to in a language like C# or Java where the variables are scoped to the block. What this means is if you declare a variable inside a loop or an if statement, it will be available to the entire function.

If you ever find yourself needing to explicitly scope a variable inside a function you can use an anonymous function to do this. You can actually create an anonymous function and then execute it straight away and all the variables inside will be scoped to the anonymous function:

    (function() {
        var myProperty = "hello world";
        alert(myProperty);
    })();
alert(typeof(myProperty)); // undefined

How does an anonymous function in JavaScript work?

Building Your First jQuery Plugin

A Plugin Development Pattern


© YBBest or respective owner

Related posts about JavaScript

Related posts about jQuery