Is there a way to determine the quantity of lines within a div using a Vue3 watcher?

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>

Answer №1

Discovering the precise number of lines within a div element that lacks line breaks proves to be a challenging task using JavaScript or CSS.

The -webkit-line-clamp feature truncates text to a designated number of lines but fails to disclose the actual line count.

One potential resolution involves manually tallying the lines by identifying the newline characters present in the text. However, this method relies on the assumption of unformatted text.

An alternative approach entails utilizing advanced techniques like leveraging the Range and BoundingClientRect APIs in JavaScript to accurately gauge the text's height and determine the line count. Nevertheless, this method may pose challenges in terms of consistency across various browsers and platforms.

It is worth noting that counting lines inside a text box might not offer an optimal solution for conditionally displaying or hiding CTA links based on text truncation. Utilizing the -webkit-line-clamp property to restrict the text container's height and employing CSS to toggle the visibility of the CTA link based on the container's height can circumvent the need for manual line calculations and ensure better compatibility across different platforms and browsers.

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 server returned a response that was void of any content

I have encountered an issue while trying to retrieve data from my server. The request works perfectly fine when tested with Postman, returning the expected data. However, upon implementing the request in my application, I receive an empty object with prope ...

Exploring Angular.js: Finding the correct path in a JSON array

Within my Angular application, I have a $scope variable defined as follows. $scope.roleList2 = [ { "roleName" : "User", "roleId" : "role1", "children" : [ { "roleName" : "subUser1", "roleId" : "role11", "collapsed" : true, "children" : [ ...

Having trouble with the Ajax load function not functioning in your HTML code?

The issue has been resolved. Thank you to everyone who helped! Initially, I was attempting to run a file offline instead of on a web server (XAMPP server). Once I uploaded the file to the web server, it started working properly. I had been trying to load ...

When an empty array is returned from a catch statement in an async/await method, TypeScript infers it as never

Function getData() returns a Promise<Output[]>. When used without a catch statement, the inferred data type is Output[]. However, adding a catch statement in front of the getData() method changes the inferred data type to Output[] | void. This sugge ...

What steps should I take to resolve the issue of my endpoint failing to accept POST requests?

I am in the process of developing a customized API, with an endpoint that is specified as shown below: https://i.stack.imgur.com/sZTI8.png To handle the functionality for this endpoint, I have set up a Profiling Controller. Inside my controller directory ...

Develop universal style classifications for JSS within material-ui

Currently, I am utilizing the JSS implementation of material-ui to style my classes. As I have separated my components, I find myself dealing with a significant amount of duplicated code in relation to the components' styles. For instance, I have mu ...

Adjust slider value dynamically with jQuery

I am working on a UI slider that ranges from 0 million to 20000 million. My goal is to change the displayed value when it reaches 1000 to show '1 milliard', and at 20000 to show '20 milliard'. For instance, if the value is 1100 millio ...

Attempting to retrieve exclusively the checked records in Vue.js

Currently, I am referring to this library for checkboxes. As I delve into the code, I notice how it is declared and utilized. Initially within the el-table, we have @selection-change="handleSelectionChange". They have initialized an empty array ...

Retrieve a JSON object from a Knockout observable array using the object's ID

I'm struggling to find examples of ko.observablearrays that deal with complex JSON objects instead of simple strings. I have an observable array containing a large JSON object with several properties, and I need to retrieve a specific object based on ...

Error message in React Js indicating the absence of a specified file or directory: "Package.json cannot

When I try to run npm start, I encounter the following error - PS D:\React\operations_app_tut> npm start npm ERR! path D:\React\operations_app_tut\package.json npm ERR! code ENOENT npm ERR! errno -4058 npm ERR! syscall open npm ...

Retrieve the boolean value associated with a checkbox

I inherited a project from another developer. The code is able to retrieve data from the text input fields in the form, but not from the checkbox inputs. The previous developer implemented these functions (among others): protected function getObjectStrin ...

Display HTML code within a data attribute

I have a function that modifies an element from OpenLayers. In the official documentation, it mentions that the property label accepts either HTML or a string. methods: { onUpdatePosition (coordinate) { this.deviceCoordinate = coordinat ...

Is it possible to use square brackets in conjunction with the "this" keyword to access a class property using an expression?

export class AppComponent implements OnInit { userSubmitted = false; accountSubmitted = false; userForm!: FormGroup; ngOnInit(): void {} onSubmit(type: string): void { this[type + 'Submitted'] = true; if(this[type + 'For ...

What steps should be taken to properly assess an AngularJS provider setup?

My provider definition looks like this: (function(angular) { angular.module('myModule', []) .provider('myService', function () { var service = {}; service.configureSomething = function () { }; service.$get = function () { ...

Searching for attributes in a JSON document

Currently, I am dealing with a results API that provides me with a JSON file. My goal is to search for a specific property within this file. To achieve this, I first push the JSON data into an empty array and then iterate over it to retrieve the first obje ...

Having trouble accessing req.user on my Node.js server using Auth0 and Angular

Currently, I am utilizing auth0 for my admin panel's login system and it is functioning smoothly. However, I have encountered an issue in node where 'req.user' is returning as undefined for some unknown reason. This setup is fairly basic; I ...

show additional worth on the console

Just starting out with JavaScript. Trying to display additional values in the console. Uncertain about how to access add-ons. Can anyone help me troubleshoot? Here is my code snippet below: https://jsfiddle.net/6f8upe80/ private sports: any = { ...

Handling exceptions in AngularJS router-ui resolve functionality

In my app, I have the parent route listed below: .state('app',{ url: '/app', templateUrl: 'views/app.html', resolve: loadSequence('modernizr','moment'), ...

Switching visual representation that appears upon clicking the dropdown menu

Issue with Duplicating Dropdown and Image Change const image = document.querySelector('.item__img'); const checkbox = document.querySelectorAll('.imgOption'); function handleChange() { let imgsrc = this.getAttribute("data-value ...

Is there a way to tally the frequency of a specific property appearing in one array within another, and then transfer those matches into a separate array?

My goal is to match the fk_city with the $id of each city in the 'list_cities' array, and then calculate the number of occurrences. const list_cities = [ { $id: '15FG', name: 'Pittsburg' }, { $id: '50HS', name: & ...