Making D3 tip to calculate its direction automatically
I was working on a small VSO gantt chart tile project with D3 and we needed to add tooltips for each bar. The problem came up when we need to display the tooltips in different directions depending on the position of the hovering bar as well as the container (VSO tiles in my example). Here is the solution for it:
First of all, there was a little bug (IMO) of d3tip itself that the classname of the tooltip didn’t get reset. For example, once it has “n” class, it always is “n”. If you change it to “w”, it will append “w” to current classname. The fix is simple, open the d3 tip source code and look at tip.show function.
OK, let’s get to the real bussiness here. How do we calculate the direction for tooltips? Here is how the documentation suggests( we use callback function when initializing tip object):
First of all, we need to know the width of the tooltip element. Why? Because if the tooltip is too big, and there is not enough room for showing it then it might be cut off. By default, d3tip will not allow you to access tooltip element inside callback function. That’s why you need this piece of code:
Our callback function will look like this:
We’re almost there. Here is my calculateDirection function: