Simple Jquery plugin – alternating background

JQuery is all the rage these days.  I’ve been using it a little bit over the past few months, and have been studying example usage of it on the side.  One thing you always hear about is how simple the plugin architecture is.  So, I decided to test it out, and came up with “The most basic JQuery plugin ever” (imagine music as emphasis in the background….):

Plugin (drop this in its own JS file, or within a <script type=”text/JavaScript”/> block on your page:

        



Example usage:

// The “backgroundColorizer” plugin allows you to essentially        

// color alternative odd/even rows’ background(thrilling, eh?)

        (function ($) {

            $.fn.extend(

            {

                backgroundColorizer: function (options) {

                    var defaults = { oddColor: ‘red’, evenColor: ‘blue’ };

                    var options = $.extend(defaults, options);

                    return $(this).each(function (index) {

                        var obj = $(this);

                        if (index % 2 > 0) {

                            obj.css(“background-color”, options.oddColor);

                        } else {

                            obj.css(“background-color”, options.evenColor);

                        }

                    });

                }

            });

        })(jQuery);

(put this html in a blank html/aspx/php, whatever page):

     <ul>
        <li>one</li>
        <li>two</li>
        <li>three</li>
        <li>four</li>
    </ul>
    <table>
        <tr><td>Jane </td><td>Smith</td></tr>
        <tr><td>Joe </td><td>Smith</td></tr>
        <tr><td>John </td><td>Doe</td></tr>
        <tr><td>Jane Q. </td><td>Public</td></tr>
    </table>

 

…and here are two JQuery selectors using the plugin:

        (function () {
            $('ul li').backgroundColorizer();
        })(jQuery);

        $().ready(function () {
            $('table tr').backgroundColorizer({ oddColor: 'green', evenColor: 'lightgreen' });
        });

And there you have it kids; THE MOST BASIC JQUERY PLUGIN EVER!!!!!!!!!!!!!!!!!!!!!!!!!……

Advertisement

1 comment so far

  1. [...] Posted February 14, 2010 Filed under: 1763993 | OK, so I’m taking the cheesy backgroundColorizer plugin to a different place because of this guy’s super clever trick.  Couple things had to [...]


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 )

Connecting to %s

Follow

Get every new post delivered to your Inbox.