Skip to content

Instantly share code, notes, and snippets.

@jfreels
Last active November 23, 2021 10:24
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jfreels/6735318 to your computer and use it in GitHub Desktop.
Save jfreels/6735318 to your computer and use it in GitHub Desktop.
d3js: Create divs using d3.js

d3js: Create divs using d3.js

<!DOCTYPE html>
<meta charset='utf-8'>
<html>
<head>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<link rel='stylesheet' href='style.css'>
</head>
<body>
<script type='text/javascript' src='script.js'></script>
</body>
</html>
var height = 200
var width = 500
var data = [
{ "class" : "topLeft",
"top" : 10 + "px",
"left" : 10 + "px",
"backgroundColor" : "yellow" },
{ "class" : "topRight",
"top" : 10 + "px",
"left" : 10 + width + "px",
"backgroundColor" : "blue" },
{ "class" : "bottomLeft",
"top" : 10 + height + "px",
"left" : 10 + "px",
"backgroundColor" : "red" },
{ "class" : "bottomRight",
"top" : 10 + height + "px",
"left" : 10 + width + "px",
"backgroundColor" : "green" }
]
var body = d3.select('body')
.selectAll('div')
.data(data).enter()
.append('div')
.attr('class', function (d) { return d.class; })
.style('position','absolute')
.style('top', function (d) { return d.top; })
.style('left', function (d) { return d.left; })
.style('width', width + "px")
.style('height', height + "px")
.style('background-color', function (d) { return d.backgroundColor; })
// add mouseover effect to change background color to black
.on('mouseover', function() {
d3.select(this)
.style('background-color','black')
})
.on('mouseout', function () {
d3.select(this)
.style('background-color', function (d) { return d.backgroundColor; })
})
/* CSS Here
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment