Is it possible for me to determine the quantity of lines present in the text without any

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>

Answer №1

To achieve the desired outcome, one method is as follows:

  1. Determine the height of a single line of text.
  2. Calculate the height of the entire content (utilizing scrollHeight for this purpose).
  3. Subsequently, divide the content height by the line height to ascertain the total number of lines.
// Additional code
watch(information, () => {
  // Employ watch to monitor modifications in the 'information' ref
  const element = information.value;
  if (element) {
    const computedStyle = window.getComputedStyle(element);
    const lineClampValue = computedStyle.getPropertyValue('-webkit-line-clamp');

    // Compute line height
    const lineHeight = parseFloat(computedStyle.lineHeight);

    // Determine content height
    const contentHeight = element.scrollHeight;

    // Determine the line count
    const textLineCount = contentHeight / lineHeight;

    isTextTruncated.value = textLineCount > Number(lineClampValue);
  }
});

VIEW CODE DEMO

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The conceal feature doesn't appear to be functioning properly on jQuery Mobile

I am facing an issue with a small mobile app built using jQuery Mobile. Within a div, I have three buttons and other content. My goal is to hide these three buttons if the user's device is running on Windows (WP). The buttons are defined as follows: ...

What is the best way to maintain whitespace in CSS while disregarding line breaks?

The white-space property in CSS-3 offers the pre-wrap value, which maintains whitespace and line breaks while wrapping as needed, along with the pre-line value that collapses whitespace but retains line breaks and wraps when necessary. However, there is c ...

Incorporate a horizontal scrollbar feature within an HTML section

Currently, I am in the process of learning vue js and would like to create a layout that includes two sections. The first section should occupy 3 grids on the screen, be fixed, and not scrollable, with a division into 4 vertical parts. The second section s ...

Solutions for Showing Pop-up Tabs in React Native Webview

I have a website that displays content based on user subscription status. If the subscription is active, a book is loaded; otherwise, if it's expired, a specific page is shown: https://i.sstatic.net/HLv0B.png To enhance user experience, I preload th ...

JavaScript code for modifying style properties

Is there a way to modify this function so that when the heading is changed successfully, a "Change Back!" button appears? And then, with a click on the button, the heading is reset and the button disappears again. function changer () { var textArea = ...

Replicate the cursor to make it show up twice

Is there a way to create a duplicate cursor effect on my website, making it appear twice and perhaps look like it's drunk? I want the cursor to still interact with images and change accordingly, but always have two visible. Can this be achieved easily ...

Tips for placing a background color *behind* a bootstrap button

When a button is clicked, I want to display an input with a background surrounding both the button and the input. Currently, my markup renders like this: https://i.sstatic.net/rxaPt.png So when the button is clicked, I need a yellow (alert-warning) backg ...

Utilizing pure CSS to target the first and last classes

I want to use pure CSS to select only the first and last classes throughout the entire document. In my scenario, the structure looks like this: <div class="Container"> <div> <div class="Parent"></div> <pre> ...

Error: jQuery function xxxx is not defined

Upon initial launch of the mobile app homepage, an error is encountered. The error message "TypeError: Jqueryxxxxxx is not a function" is displayed, although the API callback results are shown as "jQuery111309512500500950475_1459208158307({"code":1," ...

The method $event.stopPropogation doesn't seem to be functioning properly

I am facing an issue where the functionality of a div is affected when clicking on an input box inside it. When the div is selected and colored red, clicking on the input box within the selected div causes the div to become unselected (grey in color). I ...

Inconsistencies in Executing JavaScript Methods Between Mobile Safari and Android Chrome

I have a JavaScript method that appears like this: function onAction() { getValue1(); getValue2(); getValue3(); } When I invoke onAction(), I notice a discrepancy in behavior between Mobile Safari and Android Chrome. In Safari, all three meth ...

Is there a way to change a model attribute in JSP based on the AJAX response?

I have a JSP page that contains the following code snippet: <li id="notifications"> <c:choose> <c:when test="${empty alerts}"> <p class="text-default">There are no Service Reminders at this time</p> ...

What is the best way to use jQuery to insert this block of HTML into a page from a JSON response?

<script type="text/javascript"> var dataString2 = 'run=captchagood&comment=' + comment; $.ajax({ type: "POST", url: "process.php", data: dataString2, dataType: "json", error: 'error', success: function ...

The integration of Vue JS is not displaying properly in an Electron application

My electron app is loading Vue JS 2 from my local machine, but when I attach my el to an element, it completely empties the element and replaces its contents with a Vue JS comment. What could be causing this issue? index.html <!DOCTYPE html> <htm ...

Adding a hash to asset paths in NextJS static builds

After running next build && next export, I receive a directory named out, which is great. When examining the source code, such as in the index.html file, it requests assets from <link rel="preload" href="/_next/static/css/styles.aa216922.chunk. ...

Ways to turn off textarea resizing

Is there a way to prevent horizontal resizing on a textarea while still allowing vertical resizing? I find that the textarea often disrupts the design of my contact us page. If anyone has a solution for disabling the horizontal resize feature, please shar ...

Incorporate image into Vue.js form along with other information

I have been successfully sending the content of multiple fields in a form to the Database. Now I am looking to add an additional field for uploading images/files and including it with the other form fields, but I am unsure about how to accomplish this task ...

Padding among the series items within the plot of the Apex Charts donut chart

I am trying to replicate a donut chart in apex charts that is similar to the one displayed on the right. While I have made significant progress, I am still in need of adding stroke or padding around the series items on the donut chart plot, as shown in the ...

Is it possible for jQuery to create two separate variables with identical names?

When it comes to declaring variables in jQuery, you have 2 different options: The jQuery method The JavaScript method Are these two statements equivalent: $variable = "string"; And: var variable = "string"; Or do they create separate variables? ...

Applying the active state to the link will cause it to inherit the default styles of the

I am facing a challenge with overriding the active style of links in a universal manner, to restore them to their original state when they cannot be interacted with (such as during scrolling). In my current code, I implemented this: .scrolling a:active { ...