D3.js makes axis ticks clickable

I was wondering if anyone knows a way to make the labels on the axis clickable. Right now, my axis is created as follows:

// Add an x-axis with label. svg.append("g") .attr("id", "xaxis") .attr("class", "x axis") .attr("transform", "translate(" + (margin.left + margin.left_padding) + "," + height + ")") .attr("text_anchor", "top") .call(d3.svg.axis().scale(x).orient("bottom")) .selectAll("text") .style("text-anchor", "end") .attr("font-size", "12") .attr("dx", "-.8em") .attr("dy", ".15em") .attr("transform", function(d) { return "rotate(-45)" }) // Add a y-axis with label. svg.append("g") .attr("id", "yaxis") .attr("class", "y axis") .attr("transform", "translate(" + (margin.left + margin.left_padding) + "," + 0 + ")") .attr("text-anchor", "right") .call(d3.svg.axis().scale(y).orient("left")) .selectAll("text") .attr("font-size", "12") } 

I am wondering how to make it possible for each number / label on the axis to have an onclick event.

+7
source share
1 answer

You can select them with d3 and then bind a function to them with .on('click', function)

For your code, it looks something like this:

 d3.select('#xaxis') .selectAll('.tick.major') .on('click',clickMe) function clickMe(){alert("I've been clicked!")} 

Note that this will select the entire tick, and not just the text, since .tick.major is a group class that contains both the label label (text) and the tick itself (SVG line).

You can also use d as an argument to a function that you call on your ticks. If you do this, d will contain the check mark. For example, the following message will send a warning containing each checkmark value:

 d3.select('#xaxis') .selectAll('.tick.major') .on('click',clickMe) function clickMe(d){alert(d)} 

Note that you can call .major instead of .tick.major if only the main ticks have class major .

+14
source

All Articles