mcmwhfy - 1 year ago 75

jQuery Question

how do I achieve this grid using jQuery and adding that background using .css() method ?

I have tried using

`eq()`

`index()`

`filtering()`

I need to return only corner elements and for middle I need to return each element to treat separately.

Answer Source

You have to iterate over all cells and use `if`

statement to check what background should be appended to that cell. See JSFiddle.

```
var c = $('.row'), x, y, c1, c2,
cols = [
135, 203, 205,
235, 164, 158,
197, 191, 88,
214, 117, 165
];
for(y = 0; y < c.length; y++) for(x = 0; x < c.length; x++){
c1 = Math.abs(x - 2.5);
c2 = Math.abs(y - 2.5);
if(c1 > 1 && c2 > 1) x < 3 ? setBg(x, y, 166, 233, 197) : setBg(x, y, 168, 156, 197);
else if(c1 < 1 && c2 < 1) setBg(x, y, cols.shift(), cols.shift(), cols.shift());
}
function setBg(x, y, r, g, b){
c[y].children[x].style.background = 'rgb(' + r + ',' + g + ',' + b + ')';
}
```