user1804737 - 1 year ago 56

Javascript Question

I am trying to print x number of rectangles per line with d3.js

`var rectangle = svgContainer.selectAll("rect").data(data).enter().append("rect")`

.attr("x", function(d,i){ return i*5})

.attr("y", function(d,i){ return i+1})

.attr("width", 50)

.attr("height", 50)

I know I need to modify the y attribute, but I feel like I'm blindly changing values until my rectangles print like

`[][][][][][]`

[][][][][][]

[][][][][][]

instead of

`[[][[][[[][[][[][[]`

or

`[]`

[]

[]

[]

Can I have some insight on how to come up with a formula to print accordingly?

Thank you

Answer Source

Something like this...

```
var rectangle = svgContainer.selectAll("rect").data(data).enter().append("rect")
.attr("x", function(d,i){ return (i%5) * 60})
.attr("y", function(d,i){ return Math.floor(i / 5) * 60})
.attr("width", 50)
.attr("height", 50)
```

Your rects are height and width 50 so the 60 should ensure some gaps between them. 50 will result in no gaps and less than 50 overlapping rectangles.

% is the remainder operator we want the remainder after dividing by 5.