Is it feasible to determine the number of text lines in a div without line breaks? I am looking to dynamically display or hide my CTA link based on whether the text is less than or equal to the -webkit-line-clamp value:
SCRIPT:
const isExpanded = ref(true);
const information = ref();
const isTextTruncated = ref(false);
const toggleCta = computed(() => isExpanded.value ? 'show' : 'hide');
watch(information, () => {
// Implementing watch function to track changes in the 'information' ref
const element = information.value;
if (element) {
const computedStyle = window.getComputedStyle(element);
const lineClampValue = computedStyle.getPropertyValue('-webkit-line-clamp');
const textLineCount = [CALCULATION NEEDED TO DETERMINE TEXT LINE COUNT IN THE DIV]
isTextTruncated.value = textLineCount > lineClampValue;
}
});
Template:
<div ref="information" :class="isExpanded ? 'truncate' : ''">
{{ data?.information }}
</div>
<span
v-if="isTextTruncated"
@click="isExpanded = !isExpanded"
>
{{ toggleCta }}
</span>
STYLES:
.truncate {
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
}
OUTPUT:
<div class="truncated">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Maxime mollitia,
molestiae quas vel sint commodi repudiandae consequuntur voluptatum laborum
numquam blanditiis harum quisquam eius sed odit fugiat iusto fuga praesentium
optio, eaque rerum! Provident similique accusantium nemo autem. Veritatis
obcaecati tenetur iure eius earum ut molestias architecto voluptate aliquam
nihil, eveniet aliquid culpa officia aut! Impedit sit sunt quaerat, odit,
tenetur error, harum nesciunt ipsum debitis quas aliquid. Reprehenderit,
quia.
</div>