2
votes

I want to make my y axis ticks clickable, so I can request some data in the background depending on which tick was clicked.

My axis is <g class="y axis" id="yaxis"> and inside there are ticks like this:

<g class="tick" transform="translate(0,0)" style="opacity: 1;">
 <line x2="-6" y2="0"></line>
 <text dy=".32em" x="-9" y="0" style="text-anchor: end;">1547</text>
</g>

I want to be able to click the text (ok if the whole tick registers the click) and be able to use the value of it ("1547" here) in a function.

I looked through previous questions without luck but used them as base:

d3.js make axis ticks clickable

How to make axis ticks clickable in d3.js/dimple.js

What I tried

So far I only have been successful in adding a click event listener to the whole y axis which is not what I want. I have not managed to add a listener to each tick. Any idea what I might be doing wrong?

These work but apply one listener to the whole axis

svg.select(".y.axis").on("click", function() { console.log("click!");});
svg.select("#yaxis").on("click",function(d) {console.log("click!");});

All of these do not add listeners to the ticks

svg.selectAll(".y.axis g").on("click", function() {console.log("click!");});
svg.selectAll(".y.axis .tick").on("click", function() { console.log("click!");});
svg.select(".y.axis").selectAll(".tick").on("click", function() { console.log("click!");});
svg.select(".y.axis").selectAll("text").on("click", function() { console.log("click!");});
svg.selectAll("text").on("click", function() { console.log("click!");});
svg.select("#yaxis").selectAll(".tick").on("click",function(d) {console.log("click!");});
svg.selectAll(".tick").on("click", function() { console.log("click!");});

I am using D3 3.5.3.

1
Do you mean the SVG? I did include the axis in the question above (<g class="y axis" id="yaxis">), the ticks are inside it.bugmenot123
It would be helpful if you provide a fiddle but in theory this should work svg.selectAll('g.tick text').on('click', function(){console.log('clicked');})Alex_B
I feel so stupid right now, the ticks are created much further down in my code so obviously there is nothing to selectAll and bind to... I will post the answer in a moment... Thank you for being my rubber ducks. :)bugmenot123

1 Answers

13
votes

The solution was so easy...

I tried to add the listeners right after creating the y axis. This was before the ticks of the axis were created in my code. This means that there was nothing to select and bind to.

Once I moved the code to after the tick creation, everything worked fine.

I am using

svg.selectAll(".y.axis .tick")
.on("click", function(d) {  console.log(d);})
;

Lesson: If D3 does not bind things to things, maybe things do not exist (yet).