How to show a tooltip only when ellipsis is activated with JavaScript?

Spread the love

Sometimes, we want to show a tooltip only when ellipsis is activated with JavaScript.

In this article, we’ll look at how to show a tooltip only when ellipsis is activated with JavaScript.

How to show a tooltip only when ellipsis is activated with JavaScript?

To show a tooltip only when ellipsis is activated with JavaScript, we check if the text overflows its container before showing the tooltip.

For instance, we write

<div class="cell">hello world!</div>
<div class="cell">hello mars! kind regards, world</div>

to add the divs.

Then we write

.cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  border: 1px;
  border-style: solid;
  width: 120px;
}

to hide overflow.

Then we write

const cells = document.getElementsByClassName("cell");

const setTitleIfNecessary = (e) => {
  if (e.target.offsetWidth < e.target.scrollWidth) {
    e.target.setAttribute("title", e.target.innerHTML);
  }
};

for (const cell of cells) {
  cell.addEventListener("mouseenter", setTitleIfNecessary, false);
}

to select the divs with getElementsByClassName.

We add the setTitleIfNecessary mouseenter event handler to each element with addEventListener in a for-of loop.

In setTitleIfNecessary, we check if the text overflows its container with e.target.offsetWidth < e.target.scrollWidth.

If it’s true, then we set the title attribute to the value.

Conclusion

To show a tooltip only when ellipsis is activated with JavaScript, we check if the text overflows its container before showing the tooltip.

Leave a Reply

Your email address will not be published.