Achieve text length that does not exceed the specified limit dynamically

Is it possible to determine the length of the visible portion of text that overflows (or calculate the size of the overflow for further processing) using CSS or JavaScript?

If so, can this calculation be done dynamically (such as on window resize)?

The goal is to create a "read more" button that always remains at the end of the last visible line, regardless of screen size.

Answer №1

Creating something similar to this requires consideration of multiple factors. For example, your "text" may consist of a combination of text and various other elements like <b>, <i>, or <img>. If we assume it's solely plain text, the approach outlined below involves iteratively splitting the string into smaller sections in order to determine the text that matches the height of your original element while keeping any overflow hidden.

function getVisibleText(source)
{
    let yardstick = document.createElement(source.nodeName);
    let sourceRectangle = source.getBoundingClientRect();
    let text = source.textContent;
    
    yardstick.style.width = sourceRectangle.width + "px";
    yardstick.style.position = "absolute";
    yardstick.style.top = "-999px";
    yardstick.style.left = "-999px";
    yardstick.textContent = text;
    source.parentNode.appendChild(yardstick);
    
    let size = text.length;
    let difference = size;
    let yardstickRectangle = yardstick.getBoundingClientRect();
    let result = text;
    while((difference > 1 || yardstickRectangle.height > sourceRectangle.height) && size > 0)
    {
        difference = Math.round(difference / 2);
        if(yardstickRectangle.height > sourceRectangle.height)
            size -= difference;
        else
            size += difference;
        result = text.substring(0, size);
        yardstick.textContent = result;
        yardstickRectangle = yardstick.getBoundingClientRect();
    }
    yardstick.parentNode.removeChild(yardstick);
    
    // Trim to the last whole word
    let match = (new RegExp("\\s+\\S*?$", "g")).exec(result)[0];
    if(match)
        result = result.substring(0, result.length - match.length);

    return(result);
}

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

Managing React state with custom objects

We are currently utilizing a react table component that requires selections to be maintained across different pages. To achieve this functionality, we have implemented a Map to store the selected rows and a custom class named Selections to manipulate these ...

Adjust the width of a box-shadow using percentage values in CSS

As we work on developing our tool according to the provided design, we are facing a challenge in drawing a line within a table row using box-shadow. The requirement is to have the line cover only 30% of the row width, rather than spanning across the entire ...

Utilize the datepicker function in jQuery version 1.6.3 to select a range of dates

I need help adding a jQuery datepicker to my JSP page for selecting a date range. Below is the current code I am working with. $(function() { $( "#createdAtFrom" ).datepicker({ defaultDate: "+1w", changeMonth: true, ...

How to utilize the reduce method with an array of objects in JavaScript

Every week, a number of objects are delivered to me. Each object contains information such as date, hours, and other fields. I need to arrange these objects in an array based on the total hours for each day. Here is an example of the objects: var anArray ...

Refreshing the Canvas post-submission

I have created a form that allows users to add notes and sign on a Canvas. However, I am facing an issue with clearing the canvas after submission, as it does not seem to work properly. The rest of the form functions correctly. The goal is to clear both t ...

After incorporating an additional element, the li:nth-child(odd) selector is no longer functioning correctly

I previously had a setup where items in a list would have alternate colors using jQuery: $('ul.follows li:nth-child(odd)').addClass('alternate'); Everything was functioning properly until I introduced an a tag before the list items. N ...

When the screen width is halved, Bootstrap pushes my content downwards

<div class="container"> <img style="float:left" src="assets/images/logo.png" alt="university logo"> <h1 style="float:left;color:white;padding-top:20px;text-align:center;margin-left:10%"> Welcome To SURE Model</h1> <a ...

An issue arises when attempting to integrate ajax with colorbox

I am currently facing an issue with a WordPress plugin designed for playing videos. It seems that the developer who created it is no longer available, and now the play video button has stopped working. Upon further investigation using Firebug, I noticed ...

Closing the space between navigation bar choices

I'm currently working on my website's navbar menu and struggling to eliminate the gap between each of the navbar links. It seems that the li attributes with the class dropdown are slightly wider than the rest of the links, causing this issue. I&a ...

Arranging divs using the float property

I am currently working on a Django project where I have a large list of dictionaries in the view: 'description': [ { 'name': 'Parts', 'good': ['Engine', 'Transmission&a ...

Convert the data received from jQuery $.parseJSON into HTML code

I am using $.parseJSON to retrieve data from a specific URL. The link I receive contains {"status":"ok", "message":'<form><input type="text" name="" value=""> </form>'} Now, I want to add the "message" part to my content. $. ...

Integrating JSON with the DOM

Currently, I am searching for a library that offers a simple method to bind JSON data to existing DOM elements that have been generated by a Rails view template. The main reason behind this requirement is that my application features in-place editing (uti ...

Displaying a date and time beautifully in jQuery/JavaScript by providing the day of the week along with the specific time

Does anyone know of a Javascript library, preferably a jQuery plugin, that can take datetimes in any standard format (such as ISO 8601) and convert them into user-friendly strings like: Wednesday, 5:00pm Tomorrow, 9:00am Saturday, 11:00pm I'm not c ...

A guide on implementing the stencilFunc method in Three.js

Is it possible to utilize stencilFunc and stencilOp functions within Three.js? I attempted to incorporate code for a stencil test but encountered issues. var scene = new THREE.Scene(); var renderer = new THREE.WebGLRenderer({ antialias: true, st ...

Error Encountered during Deployment of Custom React App on Heroku due to Fetch API Issue

After developing a small app using React without CRA, I successfully deployed it to Heroku. However, I encountered an issue where a static JSON file that I created isn't fetching properly (it works fine on my local machine). Upon encountering this pr ...

Using Firebase callable functions with React Native

Can I use Firebase callable functions with React Native? I have successfully deployed an onCall function and it is visible in my dashboard. I have initialized the functions using: // Initialize Cloud Functions through Firebase firebase.functions(); The ...

Adding / Deleting a Row in a sequence of floated divs

I have a group of div elements arranged side by side with the float:left style as shown below: <div id="container"> <div id=0" style="float:left">> Stuff </div> <div id=1" style="float:left">> Stuff </div> < ...

What is the best way to get rid of a tooltip from a disabled button

I am facing an issue with my button that is disabled using ng-disabled. The problem is that the button still shows a tooltip even when it is disabled. I need to find a way to remove the tooltip when the button is disabled. Check out my Button ...

The Controller's ActionResult methods are not successfully collecting form data sent through an ajax request

I'm facing an issue with my purchase form where the purchase_return object in the controller is not receiving any data. It seems to be getting productId as 0 and productNm as null. Can someone help me figure out what's causing this issue? Here&a ...

Various Mobile Devices Display Website in Unique Ways

I've been having trouble getting my website to display consistently across different phones and could use some assistance. You can view the site at www.fpphotos.store. I have set overflow-x:auto; for the table containing the images, with CSS styles de ...