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) {

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

export const Title = {

export default Title;
Enter fullscreen mode Exit fullscreen mode

And here is the isEllipsisActive function:

function isEllipsisActive(e) {
  const c = e.cloneNode(true); = 'inline-block'; = 'auto'; = 'hidden';
  const truncated = c.clientWidth >= e.clientWidth;
  return truncated;
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)

Need a better mental model for async/await?

Check out this classic DEV post on the subject.

⭐️🎀 JavaScript Visualized: Promises & Async/Await

async await