What is the best way to include an ellipsis after a couple of lines of

Is there a way to add an ellipsis after two lines of text? I've been able to successfully implement the ellipsis in one line, but what if the text spans across two lines? And what if it's even longer than that — can we show an ellipsis after the second line?

Here is the code I'm using:

.columnFontfamily{
  white-space: nowrap; 
  overflow: hidden; 
  text-overflow: ellipsis;
}

I'm facing a specific issue where this code doesn't behave as expected. Any suggestions on how to address this problem?

Answer №1

Exploring these resources,

  1. Window.getComputedStyle(...)
  2. Element.clientHeight rather than Element.getBoundingClientRect()
  3. line-height
  4. box-sizing
  5. text-overflow (please confirm browser compatibility)

The resolution

I recommend this method for elements containing plain text only, as it simplifies the calculations.

<style>
    div /** removed white-space property **/
    {
        border: 1px black dotted; /** display borders for visibility **/
        box-sizing: content-box; /** essential to prevent padding calculation issues **/
        text-overflow: ellipsis;
        overflow: hidden;
        width: 220px;
    }
</style>
<div>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam vehicula justo at consequat blandit.
    Maecenas ullamcorper felis ac eros tincidunt, nec fermentum velit ultricies.
    Vivamus dictum dui vitae sapien pretium, quis scelerisque justo aliquam.
    Fusce id massa ut purus pharetra pellentesque.
    Donec sodales semper libero, a tempor lorem malesuada eu.
</div>
<script>
    +function()
    {
        'use strict';
        var element = document.querySelector('div');
        var style = element.ownerDocument.defaultView.getComputedStyle(element); // Using `element.ownerDocument.defaultView` to handle elements from different windows
        var lineHeight = parseInt(style.lineHeight.replace(/[a-z]+$/)); // Parsing line height without specifying units

        // Calculate height based on number of lines to show
        var NUMBER_OF_LINES_TO_SHOW = 2;
        element.style.height = (NUMBER_OF_LINES_TO_SHOW * lineHeight) + "px"; // Adjust unit according to browser preferences
    }();
</script>

(After updates from firefox 45.0.2 to firefox 46, and browser restart... Noticed possible issues with some extensions and the text-overflow feature)

Answer №2

My approach offers a quick solution, and understanding the process can lead to solving the problem.

I have devised 2 methods: one for counting line numbers and the other for returning text on a specific line based on the given lineNumber.

In this method, if the line counter exceeds 2, I extract the first 2 lines of text, create a new template, and append it to the container.

Check out my Fiddle

$( document ).ready(function() {

    function countLines() {
        var divHeight = parseInt( $(".maxTwoLine").height() );
        var lineHeight = parseInt($('.maxTwoLine').css('line-height'));
        return divHeight/lineHeight;
    }

    function GetTextLine(lineNumber){
        var lines = $('.maxTwoLine').text().split(' ');
        console.log(lines);
        for(var i = 0;i < lines.length;i++){
            if(i === lineNumber)
            {
                return lines[i];
            }
        }        
    }

    $(".clickB").click(function(){
        var lineCounter = countLines();
        if(lineCounter>1)
        {
            var allText = $('.maxTwoLine').text();
            var firstLineText = GetTextLine(0);
            var secondLineText = GetTextLine(1);
            var template = firstLineText + '<div class="ellipsisText">' + secondLineText + '</div>';         
            $('.maxTwoLine').text("");
            $('.maxTwoLine').append(template);
            allText = allText.replace(secondLineText, template);
        }
        var container = ".maxTwoLine";
    });  

});

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

Sending personalized object to MVC controller via Ajax

I am struggling to properly pass an array of custom objects and some unrelated strings to my MVC controller using an ajax request. Despite my efforts, I can't seem to get the data correctly in the controller. Below is the ajax request code snippet: ...

When displaying the date in a dd/MM/yyyy format, Angular mysteriously adds an extra day!

My datepicker saves the selected date without the time in my database, but when I display it, it shows one day ahead. After researching the issue, I found that it's a timezone problem encountered by many people. However, I am not sure how to resolve i ...

Whenever a user logs in or logs out from the child component, the app.js is not being re-rendered

I'm having trouble figuring out how to re-render the app.js function. It loads initially, but when I click the login or logout button, I need to call a function from the helper again to check the user status. Here is the code snippet for App.js: impor ...

JavaScript - Sending Form Data with Local Time

I want to automatically submit a form at a specific time of day The form should be submitted every day at "15:30:00" Here is the JavaScript code I have written: <script type="text/javascript> function initClock() { var now = new Date(); var h ...

Struggling with running TypeScript generated JavaScript files in IE11

Currently experimenting with Typescript using Visual Studio 2017. Set up a new directory in Visual studio 2017 ("Add Existing Website"), and included index.html and main.ts. This is the tsconfig.json configuration file I am using based on general recomme ...

Issues with browser tab icon disappearing upon being pushed to Github for a Vue project

I'm facing an issue where my browser tab icon is not showing up after I push my repository to GitHub. Interestingly, it shows up perfectly fine when I test it on localhost. On the left is my website hosted on GitHub, while on the right is my website ...

Creating a visual selection menu with icon options using jQuery or a similar framework

Currently, I am working on designing an HTML form that includes a field where users must select from a set of options such as sunny, cloudy, rainy, and more. I am seeking a creative alternative to using the <select> or <radio> input elements. ...

Is it possible to use CSS border-radius without any vendor prefixes?

Are there alternative methods to create rounded borders without using the -moz prefix, since this only applies to Mozilla browsers? -moz-border-radius-topleft:3%; -moz-border-radius-topright:3%; -moz-border-radius-bottomright:3%; -moz-border-radius-bott ...

Creating a unique box design with HTML and CSS

Looking to create a design layout using HTML & CSS similar to the one shown in the screenshot below. While I've made progress up to this point, I am wondering if there is a way to adjust the elements as indicated by the red lines in the screenshot ...

Integrating Jquery with React Portals for dynamic functionality

I'm currently working on a React project that involves using React Portals. While I've successfully loaded the portal in a new window with data displayed in a table, I'm facing an issue with adding the Jquery DataTable library to the table w ...

Exploring object properties within arrays and nested objects using ReactJS

Within the react component PokemonInfo, I am looking to extract the stats.base_stat value from the JSON obtained from https://pokeapi.co/api/v2/pokemon/1/. The issue lies in the fact that base_stat is nested inside an array called stats. My assumption is t ...

The functionality of React-router-dom protected routes seems to be malfunctioning

Understanding Protected Routes in React.js: While looking at the implementation of protected routes, you may notice that 'false' is being directly used in the if statement. However, even with this condition, the page is still accessible. Why doe ...

Tips for establishing communication between a React Native webView and a React web application

I am currently working on establishing communication between a webView in react-native and a web-app created with React-360 (and React). I am utilizing the react-native-webview library and following a guide for creating this communication. You can find the ...

"Implementing a button in a flask data table: A step-by-step guide

Hello, I am facing an issue with adding a button to a Bootstrap datatable in Flask (Python) using JavaScript. Any tips or solutions would be greatly appreciated. I am trying to achieve something like this: https://i.sstatic.net/NtaB3.png I have attempted ...

Refining an object by using a parent key as a filter criterion (JavaScript)

Refined JSON Data Check out this unfiltered JSON object that I am working with: info = [ {id: 1, name: "home", parent: 0, active: 1, order: 0}, {id: 2, name: "dashboard", parent: 0, active: 1, order: 1}, {id: 3, name: & ...

Implementing a feature that ensures html elements are transparent in a PDF conversion

I am in the process of converting a webpage into a format that is easily printable as a PDF, while ensuring that it maintains the same appearance. Many tools for printing to PDF do not support background images or colors, so I am attempting to overcome thi ...

Adjusting footer position and spacing between header elements using CSS

Is there a way to ensure my footer always stays at the bottom, even when my content is limited? And how can I reduce the space between two heading tags? Check out the HTML and CSS code here: https://jsbin.com/guwugaloci/edit?html,css,output View t ...

What steps can I take to ensure that only one panel is opened or expanded at any given time?

Introducing a versatile component/function that showcases a expandable card feature triggered by a button. The <Viewmore> component serves as an image placeholder, essential for SVG images utilization. import React, { useState, useRef } from "re ...

Is there a method to disregard acronyms when using title case formatting?

Query Background I currently have a compilation of TV shows that I am looking to convert into title case format. While my current code performs well on titles such as "Bojack Horseman," "Family Guy," and "Jessica Jones," it encounters difficulties with ac ...

Is it possible to determine the size of an array using the eval() function?

How come this is not functioning as expected? var issue_0 = ["a","b","c","d"]; arrayname = "issue_0"; arraylength = eval([arrayname]).length; for (i = 0; i < arraylength; i++) { I'm attempting to access different arrays based on user input, so I ...