Skip to content

Instantly share code, notes, and snippets.

@panesofglass
Last active August 29, 2015 14:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save panesofglass/60b1050d6362dee3c7fa to your computer and use it in GitHub Desktop.
Save panesofglass/60b1050d6362dee3c7fa to your computer and use it in GitHub Desktop.
d3.js - rendering a navigation tree
(function (global, Data, Nav, f) {
f(global, Data, Nav);
})(window, window.Data, window.Nav,
function app(global, data, Nav) {
"use strict";
var nav = Nav("nav.nav");
nav(data);
global.setTimeout(function () {
var newNavItem = {
name: 'test',
path: '/test'
};
/*
data.push(newNavItem);
data.splice(1, 0, newNavItem);
nav(data);
*/
}, 1000);
}
);
(function (global, f) {
global.Data = f();
})(window, function () {
return [
{
name: "home",
path: "/"
}, {
name: "reports",
children: [
{
name: "report 1",
path: "/reports/1"
}, {
name: "report 2",
path: "/reports/2"
}
]
}
];
});
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>D3 Experiments</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<nav class="nav"></nav>
<script src="d3.v3.js"></script>
<script src="nav.js"></script>
<script src="data.js"></script>
<script src="app.js"></script>
</body>
</html>
(function (global, d3, f) {
global.Nav = f(global, d3);
})(window, window.d3,
function app(global, d3) {
"use strict";
function link() {
this.append("a")
.attr("href", function (d) { return d.path; })
.text(function (d) { return d.name; });
}
function nav(data) {
function renderItem(d) {
var self = d3.select(this);
if (d.children) {
self.append("span")
.text(function (x) { return x.name; });
self.append("ul")
.classed("hide", true)
.call(nav(d.children));
} else {
self.call(link);
}
}
return function () {
var body = this
.selectAll("li")
.data(data, function (d) { return d.name; });
body.enter()
.append("li")
.transition()
.duration(500)
.attr("style", "background-color: yellow;")
.transition()
.duration(500)
.attr("style", "")
.each(renderItem);
body.exit()
.remove();
};
}
function Nav(selector) {
var el;
return function (data) {
el = el || d3.select(selector).append("ul");
el.call(nav(data));
};
}
return Nav;
}
);
.hide {
display: none;
}
.show {
display: block;
}
.nav li:hover ul.active,
.nav li:hover ul.hide {
display: block;
}
@panesofglass
Copy link
Author

Thanks to @TravisTheTechie for his help pairing on finding this solution.
Follow up goal: make this a component

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment