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

I am having trouble getting the graph to display using PHP and MySQL on Fusion Charts

I am looking to create a line graph based on data from my database. This is my first time working with Fusion Charts, so I followed the instructions in their documentation for dynamic charts. Here is the code from my PHP page: <?php include("Includes/F ...

Is there a way to modify the Java class name to consist of two separate words?

(Edited) I am completely new to android app development. My question is: How can I rename a java class with two words instead of one? My main menu consists of 3 options, each linked to a java class: public class Menu extends ListActivity{ String cla ...

"The TextInput component in ReactNative is preventing me from inputting any text

Experiencing issues with the iOS and Android simulators. Upon typing, the text disappears or flickers. I attempted initializing the state of the texts with preset values instead of leaving them empty. However, this caused the TextInput to stick to the ini ...

Is it possible to utilize $.each() in combination with $.ajax() to query an API?

I am dealing with an array containing 2 values, and for each value, I need to make an AJAX query to an API to check the stock availability. If there is stock for both values, a certain message should be executed, otherwise, a different message. This check ...

Is it possible to eliminate auxiliary routes in Angular 4?

Recently, I came across an interesting scenario with two <router-outlet> tags, one with a name property. To test this, I set up the following router mapping: export const routing = [ {path:'', pathMatch:'full', component:E ...

The function of jQuery .click() not triggering on elements within msDropDown

I'm having difficulty implementing jQuery on an Adobe Business Catalyst site. The HTML snippet below shows the structure: <div class="banner-main"> <div class="banner-top"> <section class="banner"> <div class="catProd ...

What could be causing the NoScript tag to malfunction across different web browsers?

I've incorporated the NoScript tag into my JSP pages in the head section. To avoid conflicts with tiles, I made sure not to include multiple NoScript tags. However, I am experiencing issues in Internet Explorer where it doesn't seem to be working ...

Tips for replacing default arrow icons with 'Previous' and 'Next' buttons in a Material-UI pagination element

I've been struggling to find a solution with my code provided below. Despite multiple attempts, the issue remains unresolved. import React from "react"; import { gridPageCountSelector, gridPageSelector, gridPageSizeSelector, useGridA ...

Send back alternate HTML content if the request is not made via AJAX

Last time I asked this question, I received several negative responses. This time, I will try to be more clear. Here is the structure of a website: Mainpage (Containing all resources and scripts) All Other pages (HTML only consists of elements of that ...

What is the best way to transmit the "theme" property to "Components" within a next.js application?

I'm currently working on a next.js app and dealing with the _app.tsx file: import '../styles/globals.css' import type { AppProps } from 'next/app' import { createTheme } from '@arwes/design' import { ThemeProvider, Global ...

How can I use AJAX to automatically populate a dropdown menu with cities in a PHP MVC application?

Within a PHP MVC setup, there is a file named city.php in the model section which defines a city class. The city class contains a method called getCitiesByProvince('ProvinceId') that retrieves all cities for a given province. When a user picks ...

A step-by-step guide to loading a .php file via Ajax using JQuery when an item is selected from a dropdown

I have successfully populated a dropdown list using PHP from a database on the page named admin.php. Now, I am utilizing JQuery with Ajax functionality to display information when a surname is clicked from the dropdown menu. The goal is to call employerP ...

Stack two divs together

It may seem silly, but I just can't get it to work. I'm attempting to enclose two divs with different classes in another div, but my current code is automatically closing the divs. There are multiple sets of divs with classes .panel-heading and ...

Console Error: Attempting to set the 'className' property of null object results in an

I'm experiencing difficulties setting up the code. The function should display all songs by a specific artist when their name is entered and the button is pressed. JavaScript file: /** * Utilizes AJAX to request data about artists from an online sou ...

Exploring elements in Javascript

I am attempting to retrieve values from various elements when a 'a' element is clicked. Consider the following code: <tr data-id="20"> <div class="row"> <td> <div class="btn-group"> <a data-checked= ...

Loading data dynamically in a table by utilizing the react WayPoint library

I'm currently utilizing a combination of material UI table and react-table. When the number of rows in the table exceeds around 200, the performance dips. To address this issue, I am looking to display a fixed number of rows (let's say 20 rows) i ...

Is it possible for me to use an image as a grid item?

I have a grid with 3 elements as shown below: Now, I am looking to replace the blue elements with images (they can be just placeholders). .grid-container { display: grid; grid-template-columns: 1fr 1fr; grid-auto-rows: minmax(30em, auto); justi ...

Encountering a SyntaxError while implementing lightweight-charts in NextJS

I'm encountering an issue while trying to integrate the lightweight-charts package into my nextjs project. When attempting to utilize the createChart function, I am receiving a syntax error in my Node.js console. ...\lightweight-charts\dist& ...

Incorporate a JavaScript form into a controller in MVC4

I'm facing an issue where I need to trigger a JavaScript function from within a controller method in my project. Here is the code snippet that I am using: Public Function redirectTo() As JavaScriptResult Return JavaScript("ToSignUp()") E ...

The JavaScript-generated form element will not be included in the data submitted through the POST method

While it may appear that this question has been asked before, my specific inquiry seems to be unique as I have not found a similar answer in other threads. Therefore, I am initiating a new discussion. My issue revolves around a form which contains a link ...