When utilizing an API to render text into a div, the offsetHeight function may return 0

I'm working with a div that displays text fetched from an API call. I'm trying to implement a See more button if the text exceeds 3 lines. Here is my approach:

         seeMore(){
            this.setState({
            seeMore: !this.state.seeMore
          })
         }

Within the render method

        function countLines() {
            var el = document.getElementById("about");
            var divHeight = el && el.offsetHeight;
            var lines = divHeight / 24;
            return lines;
        }

//assuming 24 as line height.

Inside the return statement

 <div>
       <div id="about" style={{WebkitLineClamp:seeMore ? '':3}}>
          {expert.bio}
       </div>
       {expert.bio !== undefined && (countLines() >= 3 && 
       <span onClick={this.seeMore.bind(this)}>{seeMore === true ? 'See less': 'See more'}</span>)}
 </div>

In my current implementation, the offsetHeight always returns 0 even when the content is present inside the div. I have added a check to only run the countLines function when there is content available, but it still gives me a 0 value for offsetHeight.

This solution works fine with hardcoded values, but fails when dealing with text retrieved from the API.

Answer №1

function calculateLines() {
        var elementHeight = document.getElementById("about").clientHeight;
        var lines = elementHeight / 24;
        return lines;
    }

Your attempt at this has been successful.

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

React: The getDerivedStateFromProps method does not allow the invocation of functions

I can't seem to figure out why I keep getting a TypeError - Cannot read property 'getTodosList' of null when trying to call the getTodosList function inside the getDerivedStateFromProps method. Furthermore, after implementing the getDerived ...

Starting a line series from the beginning of the y-axis on a bar chart using chart.js

We have a new request from the business regarding the implementation of chart.js. Take a look at the image below, which shows a combination of bar and line charts. The line chart contains only a few data points. https://i.sstatic.net/mCSlR.png Within th ...

React Grid by DevExtreme

Does anyone have a solution for adjusting the fontSize of the TableHeaderRow in a DevExtreme React Grid? Here is some code from a specific website () that I've been exploring: import * as React from 'react'; // Other imports... const Ad ...

The background color in CSS frames the text with a unique hue

Is there a way to wrap my multi-line text inside a div with a background color that automatically adjusts its size based on the text length? .multiline{ padding:0px; white-space: pre-wrap; height: 100px; width: ; margein:0px } <div style="b ...

When working with Firebase, I am required to extract data from two different tables simultaneously

When working with Firebase, I have the need to extract data from tables/nodes. Specifically, I am dealing with two tables - one called jobs and the other called organisations. The outcome I am looking for: I want to retrieve all companies that do not hav ...

Issue with dynamically added inputs rendering Jquery Masked Input ineffective

Currently facing a challenge while creating a signup form for a project. The issue lies in the functionality of my form which allows users to click an "add contact" button to dynamically generate more input boxes on the page for entering additional user in ...

What could be causing the presence of additional characters in the responseText received from the Servlet to JavaScript via Ajax?

I am currently involved in a project where I am attempting to retrieve the username from a session that was created using the code below: GetCurrentUserInfo.java package servlet; import java.io.IOException; import java.io.ObjectOutputStream; import java ...

Updating the parent's reference from a child component in Vue 3

In one of my child components, I have a component named Navbar that includes an option for logging out. <a @click="(event) => {event.preventDefault();}"> Logout </a> This Navbar component has been imported into my parent compon ...

Enhancing Accessibility of the 'Return to Top' Link

Currently, I am designing a web page that requires users to scroll extensively. To enhance the user experience, I have included a back-to-top link at the bottom of the page for easy navigation back to the top. This is the HTML markup I have implemented: ...

"JavaScript issue: receiving 'undefined' when trying to retrieve input

This code snippet is for a web app that tracks the number of losses in a game. The problem arises when trying to retrieve the value, which returns undefined. Every time I reference the username variable, it returns undefined. document.addEventListener(&a ...

What are the steps for adding a JSON file to a GitHub repository?

Could someone lend a hand with my GitHub issue? I recently uploaded my website to a GitHub repository. The problem I'm facing is that I have a JSON file containing translations that are being processed in JavaScript locally, and everything works fine ...

Issues with rendering images in the browser due to CSS inline-block layout are causing

I have encountered an issue with two divs that are set to 50% width and displayed inline-block. Each div contains an image. I expected both divs to stay on the same line, but sometimes the browser breaks the layout. Here is the HTML code snippet: <div ...

What are the steps to effectively populate a mongoose schema?

In my application, I have a model for people: const mongoose = require('mongoose'); const Schema = mongoose.Schema; const PersonSchema = new Schema({ name: String, cars: [{ type: Schema.types.ObjectId, ref: 'Cars' }] }); ...

Is it possible to modify only the text following the bold HTML tag?

Having trouble replacing both occurrences of "a Runner" with "a Team Captain" <form id="thisForm"> <table> <tr bgcolor="#eeeeee"> <td valign="top" colspan="4" style="vertical-align: top;"> &l ...

I encountered an error from DataTables when trying to set the width of the header cells using the original width of the columns

                 Help! I keep getting an error message: DataTable Uncaught TypeError: Cannot read property 'style' of undefined Does anyone have any ideas on how to fix this?   I keep seeing the following error message: Uncaught Typ ...

Using Javascript to Retrieve Object-Related Information from an Associative Array

I have a list of students' names along with the grades they achieved for the semester. How can I modify my JavaScript code to display the first names of students who earned an "A" grade based on the array provided? This is my current progress, but I k ...

Loading components dynamically with axios is a valuable feature

Can this be achieved? There is a spinner component. axios: action() { SPINNER (component) -- activate axios.get('/store', { params: { something } }) .then ((resp) => { SPINNER (component) -- ...

Tips for patiently anticipating the resolution of a new promise

Searching for a way to ensure that a promise waits until a broadcast is fired, I came across some enlightening posts on this platform and decided to implement the technique detailed below. However, it appears that the broadcastPromise does not actually wai ...

What could be preventing my bootstrap class from being applied as expected?

As a newcomer to HTML, CSS, and bootstrap, I am struggling with updating my stylesheet values in the preview. This is the button tag that I am working with: <button class="btn btn-primary btn-xl">Find out More</button> However, when ...

Ensure that autocorrect is set to suggest the nearest possible quantity form in WordPress

I'm currently in the process of creating a webshop using WooCommerce. Our quantity system is a bit unique, as we are using WooCommerce advanced quantity, which means that quantities increase by 0.72 increments (e.g. 0.72, 1.44, 2.16 etc). The +/- butt ...