I have a user-input field where individuals can enter information. The input can range from no information at all to as little as a single word or unlimited characters. However, my focus is on handling cases where the text exceeds three lines.
To address this, I have implemented -webkit-line-clamp to truncate the text if it extends beyond three lines within the container. Additionally, I have included a call-to-action button to expand or collapse the rest of the text.
Currently, I am looking for assistance in figuring out how to hide the call-to-action button if the user enters less than three lines of text (meaning the -webkit-line-clamp is not triggered), while ensuring it remains visible in the opposite scenario.
Here is the code snippet:
Truncating at 3 lines (universal solution for all screen sizes)
TEMPLATE:
<div>
<div ref="information" :class="isExpanded ? 'truncate': ''">
{{ .data?.information }}
</div>
<span
v-if="isTextTruncated"
@click="isExpanded = !isExpanded"
>
{{ toggleCtaLabel }}
</span>
</div>
STYLE:
.truncate {
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
}
SCRIPT:
const isExpanded = ref(true)
const information = ref();
const isTextTruncated = ref(false);
watch(information, () => {
// Using watch 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 = [NEED TO DETERMINE NUMBER OF LINES]
isTextTruncated.value = textLineCount > Number(lineClampValue);
}
});
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 quia.
</div>