Add tooltip component

This commit is contained in:
Alexey Koshelev
2025-02-18 19:00:22 +03:00
parent 3efb49792b
commit be579528e8
2 changed files with 94 additions and 0 deletions

View File

@ -0,0 +1,67 @@
function Tooltip(targetEl, options) {
this._init = function() {
var self = this;
var defaults = {
text: '',
xAnchor: 'center',
yAnchor: 'bottom',
align: 'center'
};
this.options = Object.assign({}, defaults, options);
this.tooltipEl = document.getElementById('tooltip');
if(!this.tooltipEl) {
this.tooltipEl = document.createElement("div");
this.tooltipEl.id = "tooltip";
document.body.appendChild(this.tooltipEl);
$(this.tooltipEl).hide();
}
targetEl.addEventListener('mouseover', function(e) {
$(self.tooltipEl).show();
self.tooltipEl.innerText = self.options.text;
self._updatePosition();
});
targetEl.addEventListener('mouseleave', function(e) {
$(self.tooltipEl).hide();
});
};
this._updatePosition = function() {
var rectTooltip = this.tooltipEl.getBoundingClientRect();
var rectEl = targetEl.getBoundingClientRect();
var yOffset = 3;
var xOffset = 0;
if(this.options.align == 'right') {
xOffset = -rectTooltip.width;
} else if(this.options.align == 'center') {
xOffset = -rectTooltip.width / 2;
}
if(this.options.xAnchor == 'right') {
this.tooltipEl.style.left = rectEl.right + xOffset + 'px';
} else if(this.options.xAnchor == 'center') {
this.tooltipEl.style.left = rectEl.left + rectEl.width/2 + xOffset + 'px';
}
if(this.options.yAnchor == 'bottom') {
this.tooltipEl.style.top = rectEl.bottom + yOffset + 'px';
} else if(this.options.yAnchor == 'top') {
this.tooltipEl.style.top = rectEl.top - yOffset - rectTooltip.height + 'px';
}
};
this.getText = function() {
return this.options.text;
};
this.setText = function(text) {
this.options.text = text;
this.tooltipEl.innerText = text;
this._updatePosition();
};
this._init();
}

View File

@ -0,0 +1,27 @@
#tooltip {
line-height: 12px;
position: absolute;
z-index: 10;
padding: 4px 8px;
border: 1px solid;
border-radius: 4px;
white-space: nowrap;
/* max-width: 200px; */
}
body.theme-light #tooltip,
body.theme-gray #tooltip {
background-color: #fff;
border-color: #c0c0c0;
}
body.theme-classic-light #tooltip {
background-color: #fff;
border-color: #cfcfcf;
}
body.theme-dark #tooltip {
background-color: #333;
border-color: #666;
}
body.theme-contrast-dark #tooltip {
background-color: #1e1e1e;
border-color: #696969;
}