jQuery - plugins continued

by Ryan Morris

HTML

<h1>Hello</h1>

JavaScript

// Create closure to support private variables and methods
(function($) {
    
    // Plugin definition.
    $.fn.hilight = function( options ) {
     
        debug(this);
        
        // Extend our default options with those provided.
        // Note that the first argument to extend is an empty
        // object – this is to keep from overriding our "defaults" object.
        var opts = $.extend( {}, $.fn.hilight.defaults, options );
     
        // todo: implement the plugin
        $(this).css({
            backgroundColor: opts.background,
            color: opts.foreground
        });
     
    };
    
    // Plugin defaults – added as a property on our plugin function.
    $.fn.hilight.defaults = {
        foreground: "red",
        background: "yellow"
    };
       
    // Private function for debugging.
    function debug( obj ) {
        if (window.console && window.console.log) {
            window.console.log( "hilight selection count: " + obj.length );
        }
    };
 
// End of closure.
 
})(jQuery);

// Now users can set defaults in their own scripts
// This needs only be called once and does not
// have to be called from within a "ready" block
$.fn.hilight.defaults.foreground = "blue";

$("h1").hilight();