Alternating Styles in jQuery (Plug-In) July 16th, 2009

Michael Hartmayer

This is a little script that I wrote, that lets you easily alternate the style of repeating class elements, or w/e elements you want to select. This is particularly useful for lists, and the like.

function($){
$.fn.styleAlternation = function(aClass, bClass) {
    var i = 0;
    return this.each(function() {
        if (++i % 2 != 0 && aClass!='') {
            $(this).addClass(aClass);
        } else if(bClass!='') {
            $(this).addClass(bClass);
        }
    });
}(jQuery);

The usage is very simple. Here’s the JavaScript:

$("#awesomeTable tr").styleAlternation("cssClass1","cssClass2");

From there, all you need to do is create your CSS. Example:

.cssClass1 { background: #000; color: #444; }
.cssClass2 { background: #999; color: #333; }

Here’s a screenshot:
Alternation Demo

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • Live
  • MySpace
  • Reddit
  • StumbleUpon

Tags: ,

This entry was posted on Thursday, July 16th, 2009 at 11:40 am and is filed under JavaScript. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

Leave a Reply