DEV Community

Cover image for [Vue 2 Snippets] Add title attribute only if needed
Mykolas Mankevicius
Mykolas Mankevicius

Posted on

[Vue 2 Snippets] Add title attribute only if needed

Today we'll create a directive which adds a title attribute if the text is truncated. like so:

Image description

We write a basic directive:

function inserted(el) {
  function setTitleIfNecessary() {
// this is the magic function which checks if Ellipsis is Active
    if (isEllipsisActive(this)) { 
      this.setAttribute('title', this.innerText);
    }
  }

  el.addEventListener('mouseenter', setTitleIfNecessary, false);
  el.__title = setTitleIfNecessary;
}

// function unbind(el: HTMLElement) {
function unbind(el) {
  if (!el.__title) {
    return;
  }

  window.removeEventListener('mouseenter', el.__title);
  delete el.__title;
}

export const Title = {
  inserted,
  unbind,
};

export default Title;
Enter fullscreen mode Exit fullscreen mode

And here is the isEllipsisActive function:

function isEllipsisActive(e) {
  const c = e.cloneNode(true);
  c.style.display = 'inline-block';
  c.style.width = 'auto';
  c.style.visibility = 'hidden';
  document.body.appendChild(c);
  const truncated = c.clientWidth >= e.clientWidth;
  c.remove();
  return truncated;
}
Enter fullscreen mode Exit fullscreen mode

Now this is not 100% foolproof. But for me it does the job!

Top comments (0)