Alternate background colors with jQuery
Posted: September 26th, 2008 | Author: Pierre Olivier Martel | Filed under: Javascript, jQuery | CommentsI did a little javascript function with jQuery this morning to alternate DOM elements background colors . The function takes in parameters an array of jQuery elements and an array of hexadecimal colors and changes the background color of each element with the next color in the array.
// Alternates the background colors of the elements passed in parameters
// elems - Array of jQuery DOM objects
// colors - Array of hexadecimal colors
function alternateBgColor(elems, colors) {
elems.each( function(index){
var colorIndex = index % colors.length;
$(this).css('background-color', colors[colorIndex]);
});
}
It’s only a three lines function but the cool thing about it is that you can alternate through as many colors as you need. I’m only using two for now but this could come useful at some point! I like how everything javascript just got easier with jQuery.
Passionate web developer living in Montreal and hacking in Ruby on Rails available for contracts and freelance work.