Skip to content

Instantly share code, notes, and snippets.

@mforando
Created August 19, 2019 20:43
Show Gist options
  • Save mforando/28e14b247dc825fa79ccf08fe5e4c546 to your computer and use it in GitHub Desktop.
Save mforando/28e14b247dc825fa79ccf08fe5e4c546 to your computer and use it in GitHub Desktop.
Reusable Click Handler Technique
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
#clickme{
border:1px solid black;
padding:15px;
cursor:pointer;
}
#clickme:hover{
background:gray;
}
</style>
</head>
<h1>You clicked on node <span><u id="selected">Selected Node</u></span></h1>
<svg>
</svg>
<h1 id="clickme">Click here to select 'A' programatically</h1>
<body>
<script>
var width = 500;
var nodes = [{"node":"A"},{"node":"B"},{"node":"C"}]
nodes.forEach(function(d){
d.y = width * Math.random();
d.x = width * Math.random();
})
var svg = d3.select("svg")
.attr("width", width)
.attr("height", width)
.style("overflow","visible")
.style("margin","25px")
svg.selectAll("circle")
.data(nodes)
.enter()
.append("circle")
.attr("r",15)
.style("fill","white")
.style("stroke","black")
.attr("cy",function(d){return d.y})
.attr("cx",function(d){return d.x})
.on("click",function(d,i){
//rather than calling handleClick directly, which passes through the d3 default (d,i,nodes)
//use the .call() functionality which passes through the d3 selection in place of (d,i,nodes)
//this allows the same .call() to be used whether the function is called on a mouseover or if called programatically.
d3.select(this).call(handleClick)
})
.style("cursor","pointer")
svg.selectAll("text")
.data(nodes)
.enter()
.append("text")
.style("fill","black")
.attr("y",function(d){return d.y})
.attr("x",function(d){return d.x})
.text(function(d){return d.node})
.style("text-anchor","middle")
.style("dominant-baseline","middle")
.style("pointer-events","none")
function handleClick(selection){
var d = selection.data()[0];
d3.select("#selected").text(d.node)
svg.selectAll("circle").style("fill","white")
selection.style("fill","red")
}
d3.select("#clickme")
.on("click",function(){
//go find the desired node, then pass that selection to the same update function
var selection = d3.selectAll("circle").filter(function(d){return d.node =="A"})
handleClick(selection)
})
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment