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

iOS Safari enlarges frameset beyond viewport limits

I am currently designing a website that utilizes a frameset featuring a horizontal split - a menu sidebar on the left and a content area. <!DOCTYPE html> <html> <head> <title>Frameset Test</title> </head> ...

Attempting to position the calendar control at the center in Visual Studio using C#

I'm currently working in Visual Studio using C# and I've encountered an issue with centering a Calendar control within a Panel. While I have successfully centered other elements such as radiobuttons, checkboxes, and textboxes in the panel, the t ...

What is the best way to create a sticky/fixed navbar that conceals the div above it while scrolling on the page?

When I am at the top of the page, I want to display the phone number and email above the navigation bar. However, as soon as I start scrolling down, I want the phone number and email to disappear and only show the navigation bar. I have attempted using fix ...

Clear existing markers from the map before inserting new markers

I have a map where initially the markers load coming from the database, Then there is a time-based Ajax request that fetches new records every minute. In my code snippet, I am using setMapOnAll(null) following the guidance from the Google Maps Documentati ...

What is the best way to obtain a link within a function() { ...}?

I am unable to provide the entire code at this moment. Here's a snippet of jquery code $('#contentBox').hover( function() { posi("5",768,"box.jpg","i need link here","some text here"); } ...

Is there a way to determine if a chosen date and time are prior or subsequent to the current date and time in an AngularJS environment?

When using a datepicker and timepicker, I have obtained a selected date and time. Now, I need to determine if this selected date and time is before or after the current date and time. For example, if the selected date is "Sat Dec 12 2015" and the selected ...

Utilizing jQuery to access data retrieved from ajaxStop

Seeking help on retrieving the json data returned from ajaxStop... I have tried accessing the data property within the event object, but it shows as undefined even though the data is being returned correctly... Cheers, Anthony UPDATE: Upon using Succes ...

Using Rails' link_to method within Bootstrap modals

I'm trying to implement a voting system where users can vote on different items displayed in a Bootstrap modal. Each item is listed as a button on the index page, and when clicked, it opens up the modal for voting. However, I'm facing challenges ...

Click to save image using jQuery

I am trying to implement a feature where clicking on an image allows users to download it. I am using the download attribute for this purpose. <a href="http://mysite.ru/userfiles/certificate_2.png" class="download-certificate-link" data-title="certific ...

Conceal a different CSS class if a certain CSS class is present on the page

I am currently working on organizing my page to distinguish between purchased and unsold products. For the items that have been bought, I am using the CSS class "winning_bid" within a div element. My goal is to hide another div with the class "price" if th ...

Relocate the bxslider carousel to the specific div clicked on

Is it possible to move the slider to the selected div when using bxslider? I have a carousel below. Currently, when you click on the controls (left/right arrows), it only moves one slide/div at a time, keeping the active div always on the left side. Howev ...

The jQuery ajax request was unsuccessful in connecting to the remote server

I've tried researching and troubleshooting, but I still can't figure out why the Ajax code is not functioning correctly. Here is my JavaScript code: $(document).ready(function(){ $("#tform").submit(function() { var varUserName ...

Adjust the dimensions of an SVG element using CSS within an li element's ::before pseudo-element

I'm working on a list where SVGs are loaded as list items. How can I adjust the height and width of the ::before pseudo-element to be 30px x 30px? Setting the height and width directly didn't work for me. Can someone assist with this? <div cl ...

Retrieving information from a tag within an iFrame and passing it to its parent document

I've come across a few example posts on this topic, but for some reason, none of them are working for me. Here is the stack view of what I'm trying to accomplish: <html> <head>...</head> <body> <div>Som ...

Highlighting Search Results in Kendo TreeView

I am currently working on a KendoTreeview project with spriteclass. My goal is to highlight both the root and child nodes with a specific search term. I have successfully implemented the search functionality, however, there is an issue that arises after th ...

When I implement the persist gate in Next.js with Redux, the flex direction automatically adjusts

I'm currently developing an app using next js and redux. An interesting issue has arisen - when I include PersistGate in my _app.js file, the flex direction mysteriously changes from row to column in index.js. There haven't been any modifications ...

The jQuery .hasClass() function does not work properly with SVG elements

I am working with a group of SVG elements that are assigned the classes node and link. My goal is to determine whether an element contains either the node or link class when hovering over any of the SVG components. However, I am encountering an issue where ...

Issues with padding and margin not displaying correctly at different screen sizes

I'm currently utilizing tailwindCSS and am facing an issue with adjusting the size of buttons based on screen sizes. I want the buttons to appear small with minimal vertical padding on desktop screens, and bigger with increased vertical padding on mob ...

Tips for creating a webpage with a spotlight effect using the mouse cursor

My goal is to create a webpage that is completely dark (as in night without any light at all) and have the mouse cursor emit a light effect to illuminate the surroundings. What tools or techniques should I use to achieve this unique effect? I've searc ...

Change a portion of the CSS background-image URL using vanilla JavaScript for a set of pictures

My current code successfully updates part of an src URL for regular images. let svgz = document.querySelectorAll(".svg"); for (let i = 0; i < svgz.length; i++) { svgz[i].src = svgz[i].src.replace("light", "dark"); } Now, ...