Home > javascript, jQuery > Create simple jQuery plugin

Create simple jQuery plugin

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

Advertisements
Categories: javascript, jQuery
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: