I was wondering if anyone knows a way to make the labels on the axis clickable. Right now my axis are generated 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'm wondering how to make it possible for each number/label on the axis have an onclick event.
I was wondering if anyone knows a way to make the labels on the axis clickable. Right now my axis are generated 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'm wondering how to make it possible for each number/label on the axis have an onclick event.
Share Improve this question asked Jun 24, 2013 at 18:49 AndrewAndrew 993 silver badges12 bronze badges1 Answer
Reset to default 15You can select them with d3 and then bind a function to them with .on('click', function)
For your code, this would look 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, not just the text, since .tick.major
is the class of the group that contains both the tick label (the text) and the tick itself (an SVG line).
You can also use d
as an argument in the function you are calling on your ticks. If you do so, d
will contain the value of the tick. For example, the following would send an alert containing each tick value:
d3.select('#xaxis')
.selectAll('.tick.major')
.on('click',clickMe)
function clickMe(d){alert(d)}
Note that you can probably call .major
instead of .tick.major
if nothing but the major ticks has the major
class.