aeshna Kashyap
aeshna Kashyap

Reputation: 145

Tooltips displayed for all charts when hovering over a point on a chart

I'm making charts using node.js and Chartist.js where I'm creating tooltips for the points using jQuery and CSS.

Now, the problem is the chart is being generated in the server and will always have the same root class ct-chart and same other classes as they are being generated by Chartist.js. Since I have multiple charts with my code, when I hover over a point on one chart it displays tooltips over all the charts rather than just that chart itself.

How can I fix this?

Here is my code:

var $tooltip = $('<div class="tooltip tooltip-hidden"></div>').appendTo($('.ct-chart'));
console.log($tooltip);

$(document).on('mouseenter', '.ct-point', function() {
  var seriesName = $(this).closest('.ct-point').attr('ct:meta'),
      value = $(this).attr('ct:value');

  $tooltip.text(seriesName);
  $tooltip.removeClass('tooltip-hidden');
});

$(document).on('mouseleave', '.ct-point', function() {
  $tooltip.addClass('tooltip-hidden');
});

$(document).on('mousemove', '.ct-point', function(event) {
  $tooltip.css({
    left: event.offsetX - $tooltip.width() / 2,
    top: event.offsetY - $tooltip.height() - 20
  });
});

Upvotes: 0

Views: 800

Answers (1)

dmgig
dmgig

Reputation: 4568

I think what's happening is that $tooltip variable contains a jquery array of all of your charts. So when you do $tooltip.removeClass('tooltip-hidden'); it is removing the class from all of them.

You need a way to distinguish between them - I'd suggest something like:

$(document).on('mouseenter', '.ct-point', function() {
  var seriesName = $(this).closest('.ct-point').attr('ct:meta'),
      value = $(this).attr('ct:value'),
      index = $(this).index(); // get the index of the point
  $tooltip.eq(index).text(seriesName);
  $tooltip.eq(index).removeClass('tooltip-hidden'); // use the index to remove only one class
});

I haven't tested this, but I think it should work. You'll have to apply this across all of your code.

I built this little test to show that when you use "appendTo", that variable gets populated with all of those elements you targeted. https://jsfiddle.net/wvLy2enm/

You should see this in your console log as well.

Upvotes: 1

Related Questions