Skip to content

Instantly share code, notes, and snippets.

@mathisonian
Created January 27, 2016 01:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mathisonian/b161bfed68a177591e1d to your computer and use it in GitHub Desktop.
Save mathisonian/b161bfed68a177591e1d to your computer and use it in GitHub Desktop.
var svg = d3.select('#example-3')
.append('svg')
.attr('width', '100%')
.attr('viewBox', '0 0 202 202');
var data = d3.range(10).map(function (d, i) {
return i;
});
// draw a rect to act as an outline
svg.append('rect')
.style('fill', '#888')
.attr('width', 202)
.attr('height', 202);
var rect = svg.selectAll('g')
.data(data)
.enter()
.append('g')
.selectAll('rect')
.data(data)
.enter()
.append('rect')
.attr('x', function(d) {
// offset by 1 to account for outline
return d * 20 + 1;
})
.attr('y', function() {
var i = d3.select(this.parentNode).datum();
// offset by 1 to account for outline
return i * 20 + 1;
})
.attr('width', 20)
.attr('height', 20)
.style('fill', function(d) {
var i = d3.select(this.parentNode).datum();
if ((i + d) % 2 !== 0) {
return 'black';
}
return 'white';
});
rect.on('click', function() {
d3.select(this).style('fill', "hsl(" + Math.random() * 360 + ",100%,50%)");
});
rect.on('mouseenter', function() {
d3.select(this).style('fill', 'green');
});
rect.on('mouseleave', function(d) {
var i = d3.select(this.parentNode).datum();
var f = 'white';
if ((i + d) % 2 !== 0) {
f = 'black';
}
d3.select(this).transition().style('fill', f);
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>
</head>
<body>
<div id="example-1" style="width: 400px;"></div>
<script type="text/javascript" src="./app.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment