jQuery Plugin Tutorial Part III - The Beginning

Before we start, do you know what the following code does?
(function(msg){
    alert(msg);
 })("Hey!");
Its called a self executing function.  In this code the String "Hey!"  will be passed to the anonymous function and the function will execute. You can see it in action here. If you want to learn more about self executing functions, take a look at this article on self executing functions.
I mentioned this because we will be adding our plugin to jQuery inside such a function. The following is a very simple jQuery plugin that will make the matched elements disappear.
(function($){
    //our plugin code
    $.fn.disappear = function(){
        this.each(function(){
            $(this).fadeOut("slow");
        });
    };
 }
)(jQuery); 
Now you can use this plugin to make elements disappear as follows.
$("p").disappear();
Will make all "p" or paragraph elements disappear. The $("p") part will match all paragraph elements and pass them to our function. And inside our function, we make each element fade out. You can see the code in action here.
If you remember in tutorial two, it was mentioned that jQuery supports chaining of function calls. Our above code does not support this. So in order to make sure that we don't break the chainability we  return the elements that were matched as shown below.
(function($){
    //our plugin code
    $.fn.disappear = function(){
        return this.each(function(){
            $(this).fadeOut("slow");
        });
    };
 }
)(jQuery);
Now we can chain functions like shown below. 

$("p").disappear().fadeIn();
You can see how the code works at this jsFiddle.

No comments:

Post a Comment