Today we'll create a directive which adds a title attribute if the text is truncated. like so:
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;
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;
}
Now this is not 100% foolproof. But for me it does the job!
Top comments (0)