How to trigger click on canvas object and DOM element that is placed on top of object at the same time?

  canvas, fabricjs, html, javascript

I have some circles that can be added to a fabricjs canvas. Each circle is an object, while outside my javascript code I have a DOM element, that looks like this:

<span id="cirkel1" class="carttip inlineflexmenu" style="border-radius:100%;width: 25px;height:25px;z-index:9999999;position:absolute;cursor:pointer;">
  <div class="tooltipcontent darktext tooltippadding" style="position:relative;">
    Testtest
  </div>
</span>

This element triggers a tooltip with Tippjs (a js tooltip package), that has the following code (don’t mind the each loop, I should also mention below code is outside the canvas function):

$( "#cirkel1" ).each(function( i ) {
  tippy(this, {
    theme: 'blue',
    trigger: 'click',
    allowHTML: true,
    placement: 'right',
    animation: 'scale-subtle',
    interactive: true,
    content: function (reference) {
      return reference.querySelector('.tooltipcontent');
    }
  });
});

Inside my function where I declare everything for the canvas, I have the following code to place the DOM element on top of the canvas object:

fabric.Canvas.prototype.getAbsoluteCoords = function(object) {
  return {
    left: object.left + this._offset.left,
    top: object.top + this._offset.top
  };
}

var cirkel1tooltip = document.getElementById('cirkel1'),
btnWidth = 40,
btnHeight = 40;

function positionBtn(obj) {
  var absCoords = canvas.getAbsoluteCoords(obj);
  cirkel1tooltip.style.left = (absCoords.left - btnWidth / 10) + 'px';
  cirkel1tooltip.style.top = (absCoords.top - btnHeight / 10) + 'px';
}

This works, and the tooltip shows when clicked, but in my canvas function I also have a click function which toggles an image for a specific circle when clicked. I need both to trigger at the same time when the circle is clicked, now when I click a circle, the image appears, but only after I click a second time, the tooltip appears too, not at the same first click.

Removing the image by clicking a second time also doesn’t work untill I click on another circle and then click back on the previously clicked circle.

The strange thing is, when I remove one of the two functions (tooltip click, or image toggle click) it works instant, but together only the image toggle works right away but the tooltip only after a second click. Why is that?

The entire code can be seen here (click the small circles to test): https://codepen.io/twan2020/pen/jOVaWMm

Source: Ask Javascript Questions

LEAVE A COMMENT