var square = 20, w = 900, h = 600; var tcColours = ['#FDBB30', '#130C0E', '#EC008C', '#EE3124', '#F47521', '#7AC143', '#00B0DD']; // create the svg var svg = d3.select('#grid').append('svg') .attr({ width: w, height: h }); // calculate number of rows and columns var squaresRow = _.round(w / square); var squaresColumn = _.round(h / square); // loop over number of columns _.times(squaresColumn, function(n) { // create each set of rows var rows = svg.selectAll('rect' + ' .row-' + (n + 1)) .data(d3.range(squaresRow)) .enter().append('rect') .attr({ class: function(d, i) { return 'square row-' + (n + 1) + ' ' + 'col-' + (i + 1); }, id: function(d, i) { return 's-' + (n + 1) + (i + 1); }, width: square, height: square, x: function(d, i) { return i * square; }, y: n * square, fill: tcColours[_.random(0, tcColours.length)], stroke: 'none' }); }); // use each to change the squares randomly function setColours() { d3.select(this).attr('fill', tcColours[_.random(0, tcColours.length)] ); } d3.selectAll('.square').each(setColours); // repeat till dizzy setInterval(function (){ d3.selectAll('.square').each(setColours); }, 1000);