Misha Moroshko Misha Moroshko - 6 months ago 15
Javascript Question

How to color every second row using jQuery when the number of element in a row is variable?

Consider the following example which should color every second row: (live demo here)

JS:

$(function() {
var wrapper = $("<div></div>")

for (i = 0; i < 100; i++) {
wrapper.append("<span></span>");
}

$("body").append(wrapper);

color_rows();
});

function color_rows() {
$("span").each(function(i) {
if (i % 10 >= 5) {
$(this).css("background-color", "red");
}
});
}


CSS:

div {
width: 450px;
height: 400px;
background-color: #ccc;
overflow: auto;
}
span {
display: inline-block;
width: 50px;
height: 50px;
background-color: #777;
margin: 0 30px 30px 0;
}


The output is:

enter image description here

As you can see,
color_rows()
function assumes that there are 5 elements per row. If, for example, I change the width of the
div
to be
350px
, the
color_rows()
function will not work properly (i.e. will not color every second row).

How could I fix
color_rows()
so that it will work for every width of the
div
?

Answer

this is my solution:

this works based on the top offset of each element and by comparing the it to the top offset of last element in the loop it detects if new row is seen or not, and then based on the number of row colors rows.

function color_rows() {
    var lastTop = -1;
    var rowCount = 0;
    $("span").each(function(i) {
        var top = $(this).position().top;
        if (top != lastTop) {
            rowCount++;
            lastTop = top;
        }
        if(rowCount % 2 == 0)
        {
            $(this).css("background-color", "red");
        }
    });
}

jsFiddle: http://jsfiddle.net/Ug6wD/4/