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)


11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields


Read the whole post now!