Creating a Jquery method to handle multi-line ellipsis for long text

Check out this fiddle I made: http://jsfiddle.net/mupersan82/JYuSY/

This snippet handles multiline ellipsis:

$(function() {
var ellipsisText = $('.multilineEllipseText');
var textContainer = $('.incidentCellBottomRight').height();
while ($(ellipsisText).outerHeight(true) > textContainer) {
    $(ellipsisText).text(function(index, text) {
        return text.replace(/\W*\s(\S)*$/, '...');
    });
}

});

The original function can be found here: Cross browsers mult-lines text overflow with ellipsis appended within a width&height fixed div?

Although the function works for multiline content, it doesn't let the text reach the edges. For single-line content, the ellipsis appears after just one word.

Ideally, text should fill up to the max height of its parent div, which is set at 100px.

Answer №1

Within your code snippet, you have the following line:

var $ellipsisText = $('.multilineEllipseText');

This line selects all elements with the class .multilineEllipseText. However, later on in your code, you are utilizing .outerHeight(true), which will only return the height of the first element within that set.

As a result, this approach works for the first element, but for subsequent elements, you will be comparing their heights to that of the first element, leading to inaccurate comparisons.


To address this issue, consider the following adjustment:

var textContainerHeight= $('.incidentCellBottomRight').height();

$('.multilineEllipseText').each(function () {
  var $ellipsisText = $(this);

  while ($ellipsisText.outerHeight(true) > textContainerHeight) {
    $ellipsisText.text(function(index, text) {
      return text.replace(/\W*\s(\S)*$/, '...');
    });
  }
});

Check out the demo here: http://jsfiddle.net/JYuSY/1/

Answer №2

We trust that this information will prove beneficial to you. (dotdotdot)

Visit dotdotdot website

Answer №3

Although this answer may be outdated, I wanted to share a similar issue and solution that remains relevant.

I have a responsive website with paragraphs that need to be limited to 3 lines and expand when clicked for aesthetic reasons without refreshing the page for every screen size change.

Here is the elegant solution I came up with:

/** 
  * @name   - Ellipsify
  * @desc   - trims and adds ellipsis to element when element text height is greater than element height
  * @param  - [required] (string)identity - string containing jquery selector used to create object group (array) based on selector
  * @function : _init - calculates each element and determines need for ellipsis, then truncates text as needed
*/
var Ellipsify = function(identity) {
    if (identity) {
        this.identity = identity;
        this.group = $(this.identity);
        if (this.group.length > 0) {
            this._init();
        }
    }
};
Ellipsify.prototype = {
    _init : function() {
        var that = this;
        that.group.each(function() {
            if ($(this).children('.hidden').length > 0) {
                $(this).children(':not(.hidden)').text($(this).children(':not(.hidden)').text().replace('...',' ') + $(this).children('.hidden').text());
                $(this).children('.hidden').remove();
            }
            if ($(this).children().outerHeight() > $(this).innerHeight()) {
                $(this).append('<span class="hidden"></span>');
                while ($(this).children(':not(.hidden)').outerHeight() > $(this).innerHeight()) {
                    var paragraph = $(this).children(':not(.hidden)').text().replace('...', '');
                    var lastword = paragraph.substring(paragraph.lastIndexOf(' '));
                    $(this).children(':not(.hidden)').text(paragraph.substring(0, paragraph.lastIndexOf(' ')) + '...');
                    $(this).children('.hidden').text(lastword + $(this).children('.hidden').text());
                }
            }
        });
    },
};

The HTML structure includes:

<p><span>Big paragraph of text goes here.</span></p>

and for CSS styling:

p {
    font-size:1em;
    line-height:1.5em;
    height:4.5em;
    width:100%;
    overflow:hidden;
}
.hidden {
    display:none;
}

Answer №4

Experience full-word multi-line word-wrap with ellipsis by visiting this link: http://example.com/word-wrap-example/

To achieve this effect, simply adjust the following properties in your code:

var containerWidth = 400;
var numberOfLines = 4;

Answer №5

$(".jsgrid-cell").forEach(function(index, value){
    var textContent=$(value).text();
    if(textContent.length>100){
        var trimmedText=textContent.substring(0, 100)+
        "<span onclick='$(this).hide();$(this).next().toggle();'>"+
            "..."+
        "</span>"+
        "<span style='display:none'>"+
            textContent.substring(100, textContent.length)+
        "</span>";
        
        $(value).html(trimmedText );
    }
});

Answer №6

An efficient Jquery function designed for creating single line ellipsis text. This function can also be utilized to count characters in a textbox, span, or any other DOM element. Simply input the Text (String) and Size (Int) parameters.

// Character Count Ellipsis
function EllipsisChar(text, size) {
    var len = text.length;
    if (len >= size) {
        // add ... if text length is equal to or greater than the specified size
        text = text.substring(0, size) + "...";
    }
    else {
        // perform an action if text length is lesser
    }
    return text;
};

Here is an example of how to use this function:

var EllipsisReturnText = EllipsisChar("Sample text goes here", 10);

Result:

"Sample tex..."

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

Incorporating a unique font into your SAPUI5 application

While experimenting with an expense app design, I decided to incorporate a receipt-like font for a unique look and feel. After discovering the FakeReceipt font, I placed my woff and woff2 files in the same directory as my style.css file, and it worked like ...

Tips for ensuring that jQuery runs in the correct order within Angular 2

As a beginner with Angular 2 and asynchronous loading, I have encountered some difficulties in finding the right approach for running jQuery scripts in the correct sequence within an Angular 2 project. Despite exploring various resources such as: How to u ...

combining all JavaScript script tags into a single tag

I'm currently working with wavesurfer.js and have the following setup: 'use strict' <!-- wavesurfer.js --> <script src="src/wavesurfer.js"></script> <script src="src/util.js"></script> <scrip ...

Samsung S4 Android device experiencing interruption in HTML5 video playback

When using Android Webview to play html5 videos, including Youtube videos (using my own tags and Youtube embedded iFrames), I came across an issue with the Samsung Galaxy S4. The problem occurs in the following scenario: Play a video. Press 'back&ap ...

Looking for a custom JavaScript color wheel with advanced features?

In search of a javascript color picker/wheel that allows users to easily select colors for our paint shop. Once the color is selected, it should automatically add the color value to the shopping cart. Our online store is operated using PrestaShop, so we ...

From HTML element to pug-template with the use of the # symbol

I have a code snippet with 2 angular material radio buttons. Both of them contain the #attribute/element (I'm not sure what it's called) within them. How can I convert them into pug so that the attribute/element with the # works? Below is the sam ...

bootstrap thumbnail displayed without a border

I have decided to incorporate Bootstrap into my latest project: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS ...

Experiencing difficulties with capturing the focus event of the <select> tag

I'm completely stumped at the moment... I just can't seem to get my head around how to make a jQuery $("thing").is(":focus") selector work with a <select> tag in my project. Here's what I've got so far: <input id="uText" name ...

Collaborate on sharing CSS and TypeScript code between multiple projects to

I am looking for a solution to efficiently share CSS and TS code across multiple Angular projects. Simply copy-pasting the code is not an ideal option. Is there a better way to achieve this? ...

Preserve the height of the previous div following an AJAX request

I am currently facing an issue where I have a script that utilizes ajax to receive a response containing a cart string (html code) with items from the cart. Inside the response handler, there is another script that sets the height of each div in the cart s ...

Is there a way to retrieve the sub-child menu data from a JSON file?

I am currently working on creating a horizontal menu from a json file. However, I am facing issues in retrieving the subchild elements properly. Below is an example of my json file: var data = [{ "menu":[ { "MenuId":1, ...

Tips for retrieving the selected option from a dropdown menu

I have a dropdown menu with checkboxes that can be selected using SumoSelect. Here is the markup for the dropdown menu: <select multiple="multiple" name="somename" id="uq" class="select"> <option value="volvo">Volvo</option> <o ...

Utilizing JSON to transfer PHP array data for display using JQuery

Currently, I am working on a jQuery script that is responsible for fetching a PHP array from the MySQL database and converting it into a JSON object. The process is functioning correctly, as I can successfully output the raw JSON data along with the keys. ...

The some() method in Javascript with an extra argument

I want to validate if at least one element in an array satisfies a certain condition. The condition is based on a variable. Here's an example of how I'm currently attempting this: function checkCondition(previousValue, index, array) { retur ...

Angular is used to send an HTTP GET request

I'm seeking assistance with implementing a get and put request in Angular. I understand how to initiate a get or put request when a button is clicked, by binding the request to the button itself. However, I am now looking for a way to trigger a get re ...

Exploring JSON without taking into account letter case

Looking to conduct a case-insensitive search in a JSON file? Here's the JSON data you can work with: { "Data" : [ {"Name": "Widget", "Price": "25.00", "Quantity": "5" }, {"Name": "Thing", "Price": "15.00", "Quantity": "5" }, {"Nam ...

Bringing JQuery into your Electron project through HTML

Working on some ElectronJS HTML coding and in need of using JQuery within the HTML. I've gone ahead and installed jQuery with npm install jquery. The question is, which file do I import to make use of JQuery? <!DOCTYPE html> <html lang="en" ...

Issues with CSS transitions/animations not functioning properly across different browsers

Take a look at this FIDDLE Link. I'm facing an issue where the animation works smoothly in Firefox, but it's not functioning as expected in Chrome. Kindly open the fiddle in both browsers (Chrome and Firefox), hover over the image, and notice t ...

The Checkboxlist generated by jQuery-Ajax does not function when clicked on

I have a dynamic radio button list (rblCategories) that, when the selected value changes, triggers the creation of a checkbox list using ajax and populates it. However, I am facing an issue with updating my datatable when any checkbox is checked/unchecked ...

The grid is intended to be positioned horizontally, but is currently being shown vertically

I need help fixing the layout of my items. They are currently displaying vertically instead of in a horizontal row. Any suggestions on how to correct this? https://i.stack.imgur.com/CQ4yG.jpg <div class="col-lg-12 col-sm-12 portfolio-item"> <d ...