Issue
I have a user controlled text input where they can add information. It's possible to have no information, as little as one word or no limit but the only case I am trying to solve is is the goes over 3 lines or not.
I am using -webkit-line-clamp to truncate the text if it is more than 3 lines of the container which works perfectly and have a CTA to open/collapse the rest of the text.
What I now need some help with is how to hide the CTA if the user inserts less than 3 line (i.e. doesn't trigger the -webkit-line-clamp/truncate) but make sure it is visible if the opposite.
My code:
Truncate at 3 lines (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, () => {
// Use watch to monitor 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 = [I NEED TO CALCULATE THE 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>
Solution
One way to achieve the following result would be to:
- Get the height og one line of text.
- Get the height of the entire content(used
scrollHeight
for this purpose) - Finally, divide the content height by the line height to get the total number of lines.
// other code
watch(information, () => {
// Use watch to monitor changes in the 'information' ref
const element = information.value;
if (element) {
const computedStyle = window.getComputedStyle(element);
const lineClampValue = computedStyle.getPropertyValue('-webkit-line-clamp');
// Calculate line height
const lineHeight = parseFloat(computedStyle.lineHeight);
// Calculate content height
const contentHeight = element.scrollHeight;
// Calculate the number of lines
const textLineCount = contentHeight / lineHeight;
isTextTruncated.value = textLineCount > Number(lineClampValue);
}
});
Answered By - mandy8055
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.