I was wondering what was the best way to go about adding a button to my group elements using d3.
I have currently built my visual using d3 to look something like:
<div>
<svg>
<g>
<rect>
</g>
<g>...</g>
</svg>
</div>
So I am wondering how I would add a clickable button in each group element. Some ideas I had were:
g.append("a")
.append("image")
.attr("src", ...);
or
g.append("a")
.append("rect")
.attr(...)
Ultimately I would like the button to perform an onclick event. What is the best way to go about this?
I was wondering what was the best way to go about adding a button to my group elements using d3.
I have currently built my visual using d3 to look something like:
<div>
<svg>
<g>
<rect>
</g>
<g>...</g>
</svg>
</div>
So I am wondering how I would add a clickable button in each group element. Some ideas I had were:
g.append("a")
.append("image")
.attr("src", ...);
or
g.append("a")
.append("rect")
.attr(...)
Ultimately I would like the button to perform an onclick event. What is the best way to go about this?
Share Improve this question edited Jan 14, 2018 at 2:20 ekad 14.6k26 gold badges46 silver badges48 bronze badges asked Nov 19, 2014 at 5:32 kLaikLai 2691 gold badge3 silver badges11 bronze badges 2-
If you want an actual button you'll have to use a
foreignObject
and embed HTML. – Lars Kotthoff Commented Nov 19, 2014 at 9:31 - In the end I mainly just needed a clickable element, however thank you for the info. – kLai Commented Nov 19, 2014 at 20:14
2 Answers
Reset to default 6You can create a rect
and use d3's selection.on api to register a click listener:
var rect = d3.select('svg g rect');
rect.on('click', function() {
console.log('i was clicked');
});
.as-console-wrapper { max-height: 3.5em !important; }
<script src="https://cdnjs.cloudflare./ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg width="400" height="400">
<g transform="translate(50,50)">
<rect height="100" width="200" fill="red"/>
</g>
</svg>
Button isn't an SVG ponent, you can draw a rect or a circle(usually called legend) instead, and binding the click event on the legend.
You can refer to grouped bars with legend click event