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.