Skip to content

Instantly share code, notes, and snippets.

@jonasraoni
Last active October 1, 2021 09:20
Show Gist options
  • Save jonasraoni/be203af9decf571928c141b89aa49b6a to your computer and use it in GitHub Desktop.
Save jonasraoni/be203af9decf571928c141b89aa49b6a to your computer and use it in GitHub Desktop.
Vue directive: Tooltip on overflow for hidden text
export default class TooltipOnOverflowDirective {
static install (Vue) {
Vue.directive('tooltip-on-overflow', this.directive);
}
static directive = {
bind (el) {
for (const event of ['mouseover', 'mouseout']) {
el.addEventListener(event, TooltipOnOverflowDirective[event]);
}
},
unbind (el) {
for (const event of ['mouseover', 'mouseout']) {
el.removeEventListener(event, TooltipOnOverflowDirective[event]);
}
}
}
static mouseover ({ target }) {
if (('value' in target || (target.childNodes.length === 1 && target.firstChild.nodeType === Node.TEXT_NODE)) &&
target.offsetWidth < target.scrollWidth
) {
const value = target.textContent || target.value;
const title = target.getAttribute('title');
if (value && !title) {
target.setAttribute('title', value);
target.dataset.tooltipTitle = title || '';
}
}
}
static mouseout ({ target }) {
const title = target.dataset && target.dataset.tooltipTitle;
if (title !== undefined) {
delete target.dataset.tooltipTitle;
if (title) {
target.setAttribute('title', title);
} else {
target.removeAttribute('title');
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment