Detect CSS Ellipsis in JavaScript and a title

Detect CSS Ellipsis in JavaScript and a title

I have a collection of block elements on a page. They all have the CSS rules white-space, overflow, text-overflow set so that overflowing text is trimmed and an ellipsis is used.

No title attribute:
<div class="name ellipsis">
  jayesh
</div>
The title atrtibute is automatically added:
<div class="name ellipsis">
   jayesh patel
</div>

body {
  margin: 0;
  padding: 5px 10px;
  background: #ccc;
  font-family: Arial, sans-serif;
}

.ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.name {
  display: block;
  width: 100px;
  margin: 10px 40px;
  padding: 5px 10px;
  background: white;
  box-shadow: 0px 0px 3px black;
  font-weight: bold;
  text-transform: uppercase;
  text-align: center;
}
function isEllipsisActive(element) {
  return element.offsetWidth < element.scrollWidth;
}

Array.from(document.querySelectorAll('.ellipsis'))
  .forEach(element => {
    if (isEllipsisActive(element)) {
      element.title = element.innerText;
    }
  });
https://codepen.io/jayeshhpatel/pen/MWbNjQL

Jayesh Patel
Author
Jayesh Patel

Jayesh Patel is a Professional Web Developer & Designer and the Founder of InCreativeWeb.

As a highly Creative Web/Graphic/UI Designer - Front End / PHP / WordPress / Shopify Developer, with 14+ years of experience, he also provide complete solution from SEO to Digital Marketing. The passion he has for his work, his dedication, and ability to make quick, decisive decisions set him apart from the rest.

His first priority is to create a website with Complete SEO + Speed Up + WordPress Security Code of standards.



Explore

Related Articles

11th April, 2024

W3 Total Cache: A Comprehensive Review & Guide for 2024

8th April, 2024

Top 10 Must-Have Web Design Resources and Tools for 2024

8th April, 2024

Unleash Accessibility Potential in Front-end Development