Using .each() for shared computation.
From D3 in Depth book by Peter Cook.
| license: gpl-3.0 | |
| height: 170 | |
| border: no |
Using .each() for shared computation.
From D3 in Depth book by Peter Cook.
| <!DOCTYPE html> | |
| <meta charset="utf-8"> | |
| <head> | |
| <title>Selection .each</title> | |
| </head> | |
| <style> | |
| body { | |
| font-family: "Helvetica Neue", Helvetica, sans-serif; | |
| font-size: 14px; | |
| color: #333; | |
| } | |
| circle { | |
| fill: #ddd; | |
| cursor: pointer; | |
| } | |
| </style> | |
| <body> | |
| <svg width="760" height="140"> | |
| <g transform="translate(70, 70)"> | |
| <circle r="40" /> | |
| <circle r="40" cx="120" /> | |
| <circle r="40" cx="240" /> | |
| <circle r="40" cx="360" /> | |
| <circle r="40" cx="480" /> | |
| <circle r="40" cx="620" /> | |
| </g> | |
| </svg> | |
| <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.2/d3.min.js"></script> | |
| <script> | |
| d3.selectAll('circle') | |
| .each(function(d, i) { | |
| var odd = i % 2 === 1; | |
| d3.select(this) | |
| .style('fill', odd ? 'orange' : '#ddd') | |
| .attr('r', odd ? 40 : 20); | |
| }); | |
| </script> | |
| </body> | |
| </html> |