Skip to content

Instantly share code, notes, and snippets.

@vkuchinov

vkuchinov/README.md

Last active Sep 4, 2020
Embed
What would you like to do?
D3.JS Simplified Buttons

A simplified version of http://bl.ocks.org/pbogden/7487564 made by pbogden. You can assign every button 'click' event to different functions:

var data = [{label: "BUTTON.A", x: 100, y: 60, function: function(){ fnA(); } }, {label: "BUTTON.B", x: 100, y: 120, function: function(){ fnB(); } } ];

//Simplified version of http://bl.ocks.org/pbogden/7487564
//made by pbogden [https://github.com/pbogden]
d3.button = function() {
var padding = 10,
radius = 3,
stdDeviation = 5,
offsetX = 2,
offsetY = 4;
function my(selection) {
selection.each(function(d, i) {
var g = d3.select(this)
.attr("id", "d3-button" + i)
.attr("transform", "translate(" + d.x + "," + d.y + ")");
var text = g.append("text").text(d.label);
var bbox = text.node().getBBox();
var rect = g.insert("rect", "text")
.attr("x", bbox.x - padding)
.attr("y", bbox.y - padding)
.attr("width", bbox.width + 2 * padding)
.attr("height", bbox.height + 2 * padding)
.attr("rx", radius)
.attr("ry", radius)
.on("mouseover", mouseover)
.on("mouseout", mouseout)
.on("click", click)
});
}
function mouseover() { d3.select(this.parentNode).select("rect").classed("active", true) }
function mouseout() { d3.select(this.parentNode).select("rect").classed("active", false) }
function click(d, i) { d.function(); }
return my;
}
<!DOCTYPE html>
<meta charset="utf-8">
<title>D3.JS: Button</title>
<body>
<body>
<link rel="stylesheet" href="styles.css?v=1.0">
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="d3.button.js"></script>
<script>
var width = 960, height = 480;
var data = [{label: "BUTTON.A", x: 100, y: 60, function: function(){ fnA(); } },
{label: "BUTTON.B", x: 100, y: 120, function: function(){ fnB(); } }];
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var button = d3.button();
var buttons = svg.selectAll(".button")
.data(data)
.enter()
.append("g")
.attr("class", "button")
.call(button);
var fnA = function(){ console.log("functionA"); }
function fnB(){ console.log("functionB"); }
</script>
@import url('https://fonts.googleapis.com/css?family=Open+Sans');
body {
font-family: 'Open Sans', sans-serif;
}
.button rect {
fill: #26654F;
stroke: none;
}
.button rect.active {
fill: #2C785E;
stroke: #26654F;
stroke-width: 2px;
}
.button text {
font-family: 'Open Sans', sans-serif;
font-size: 12px;
letter-spacing: 3px;
fill: #FFFFFF;
pointer-events: none;
text-anchor: middle;
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment