jQuery - plugins basics

HTML

<h2>Lets make a jQuery plugin</h2>
<h3>Am I green yet?</h3>
<h3>what about me?</h3>

JavaScript

// Step 1
//
// What shall it do? Lets start simple...
// Make something green (straight off the docs!)
//$("h2").css({
  //  color: "green" 
//});

// Step 2
//
// Make a method available on all jQuery objects
// Extend jQuery object prototype ($.fn)

$.fn.greenify = function() {
  
    this.css({color: "green"});
    return $(this);
};

$("h3").greenify();

/**/

// Step 3
//
// make it chainable
// by returning "this"

$("h3").greenify().fadeOut().fadeIn();

var pork = 1;

do {
	$("h3").greenify().fadeOut().fadeIn();
    $("h3").on("click","", function(){
        pork = 5;
        return;
    });
}while (pork != 5);

// Step 4
//
// Make it jQuery alias-safe
// give it its own namespace with privates
/*
(function($){
    
    // can also add some private variables
    //var greenifyColor = "green";
    
    $.fn.greenify = function() {
  
        //this.css({color: greenifyColor});
        //return this
        
        // Step 5
        // Make it safe for collections (Better way, plus chaining)
        return this.each(function(){
            
            // "each" context is the DOM element... use $(this) not this.
            $(this).css({color: "green"});
            
        });
        
    };
    
    // and any other extensions...
    
}(jQuery));
/**/

// Step 6
//
// Ability to pass in settings
/*
(function($){
       
    $.fn.greenify = function(options) {
        
        var settings = $.extend({
            color: "green"
        }, options);
        
        return this.each(function(){            
            $(this).css({color: settings.color});            
        });
        
    };
    
}(jQuery));


$("h3").greenify({color: "red"}).fadeOut();
/**/