Friday, 22 January 2010

jQuery 1.4 Give Us a New Way to Zebra Stripe

In jQuery 1.4 all setter methods have been extended to take in a setter function.  Before only .attr() had the ability to use a function to return the value to set. Now you can pass a setter function to .css(), .attr(), .val(), .html(), .text(), .append(), .prepend(), .before(), .after(), .replaceWith(), .wrap(), .wrapInner(), .offset(), .addClass(), .removeClass(), and .toggleClass().

The setter function can take two arguments, the index position of the element in the set and the old value of the element.

.css( propertyName, function(index, value))

With setter functions now available we can use this in a new way to zebra stripe a set of elements.  In this example we'll stripe a unordered list:

HTML:

<ul>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
<li>item 4</li>
<li>item 5</li>
<li>item 6</li>
<li>item 7</li>
</ul>
jQuery 1.4:

$(document).ready(function(){
$("li").css("background-color", function(i){
return (i % 2 === 0) ? "#cccccc": "#FFFFFF";
});
});

We select all the LIs and call the .css() setter method. We give it the property name we want to update, background-image and we pass a function that will return the value we want to set.

The function tests if the index that we passed in i is MOD 2 (simply is it even or odd), if even set the color to #cccccc else set it to #FFFFFF.

Demo: (jsbin)

Note: Obviously, this isn't the best way to do zebra stripping with jQuery but I like to explore different ways to do the same thing to learn the techniques.

Wednesday, 27 January 2010 22:10:36 (Eastern Standard Time, UTC-05:00)
Awesome!

Could maybe improve by using addclass instead of css:

$(document).ready(function(){
$("li").addClass(function(i){
return (i % 2 === 0) ? "evenRow": "oddRow";
});
});
Monday, 01 February 2010 05:45:18 (Eastern Standard Time, UTC-05:00)
And by the way, binary operators are faster than modulo in most browsers (I already filed a trac request to incorporate this into Sizzle):

return (i & 1 === 0) ? 'evenRow' : 'oddRow';

Apart from that, you could try the support of the CSS3.0 pseudoclasses :odd/:even and only use JS if needed.

Greetings, LX
LX
Thursday, 04 February 2010 17:14:34 (Eastern Standard Time, UTC-05:00)
$('ul > li:odd').addClass('even');

plain lis have background #CCC, lis with class even has background #FFF
Ranjan Datta
Wednesday, 17 February 2010 14:09:21 (Eastern Standard Time, UTC-05:00)
Ranjan Datta +1
As for me :odd or :even usage will lead to smaller amount of code
What for such complexity
Igor
Name
E-mail
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):

Blog Posts by:

Currently Viewable:

The Official jQuery Podcast

with Ralph Whitbeck & Elijah Manor

You can subscribe to the show in iTunes or via the raw RSS feed

My Twitter Updates

View Twitter Page