Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add on-click events to D3 axis ticks

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.

like image 558
bugmenot123 Avatar asked Dec 02 '25 22:12

bugmenot123


1 Answers

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).

like image 93
bugmenot123 Avatar answered Dec 04 '25 12:12

bugmenot123



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!