Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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