kLai
kLai

Reputation: 269

Adding a button to a <g> element using d3

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?

Upvotes: 1

Views: 10279

Answers (2)

go-oleg
go-oleg

Reputation: 19480

You 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.com/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>

Upvotes: 6

huan feng
huan feng

Reputation: 8623

Button isn't an SVG component, 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

Upvotes: 1

Related Questions