How can one determine the number of characters that remain visible once text-overflow:ellipsis and overflow:hidden are implemented?

How can I display a list of email addresses separated by a delimiter ';' while preserving the original format? I also need to cut off any overflow text that exceeds one line, and then indicate the number of email addresses remaining that the user didn't see, based on certain characters like "@" and ";". Is there a way to determine the number of characters that are kept or removed from the HTML text after it's been clipped?

Answer №1

If you are unsure about your criteria, I can provide an example of how it can be calculated:

var span = document.getElementById("text");
var countSpan = document.getElementById("count");
var orig = span.innerText;
var vis = orig;

while(vis.length && span.scrollWidth > parseFloat(window.getComputedStyle(span).width)
{
  vis = vis.slice(0,-1);
  span.innerText = vis + "....";
}
span.innerText = orig;

var visibleText = vis;
var truncatedText = orig.replace(new RegExp("^" + vis.replace(/[.*+?^${}()|[\]\\]/g, '\\$&")), "");
var visibleCleanLessText;
var visibleCleanMoreText;
var truncatedCleanLessText;
var truncatedCleanMoreText;
if (truncatedText === "" || truncatedText.substr(0, 1) == ":")
{
  visibleCleanLessText = vis;
  visibleCleanMoreText = vis;
  truncatedCleanLessText = truncatedText.substr(1);
  truncatedCleanMoreText = truncatedCleanLessText;
}
else
{
  var m = vis.match(/:([^:]*)$/);
  visibleCleanLessText = m ? vis.replace(/:[^:]*$/, "") : "";
  visibleCleanMoreText = vis + (truncatedText.match(/^([^:]*):/) || ["",""])[1];
  truncatedCleanMoreText = (m ? m[1] : vis) + truncatedText;
  truncatedCleanLessText = truncatedText.replace(/^[^:]*:/, "");
}
var truncatedCount = truncatedCleanMoreText === "" ? 0 : truncatedCleanMoreText.split(":").length;
if (truncatedCount)
{
  countSpan.innerText = "+" + truncatedCount;
  span.title = orig;
}

console.log("orig              ", orig);
console.log("visible           ", vis);
console.log("truncated         ", truncatedText);
console.log("visibleCleanLess  ", visibleCleanLessText);
console.log("truncatedCleanMore", truncatedCleanMoreText);
console.log("visibleCleanMore  ", visibleCleanMoreText);
console.log("truncatedCleanLess", truncatedCleanLessText);
div
{
  vertical-align: middle;
}
.truncate
{
  width: 300px;
  display: inline-block;
  overflow: hidden;
  text-overflow: ellipsis;
  vertical-align: middle;
}

.count:empty
{
  display: none;
}
.count
{
  display: inline-block;
  position: relative;
  font-family: monospace;
  font-size: 90%;
  left: -0.5em;
  border: 1px solid black;
  border-radius: 0.3em;
  padding: 0.1em;
}
<div>
  <span id="text" class="truncate"><a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="32575f535b5e0372574a535f425e571c515d5f">[email protected]</a>;<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="46232b272f2a7406233e272b362a236825292b">[email protected]</a>;<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e6838b878f8ad5a6839e878b968a83c885898b">[email protected]</a>;<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fa9f979b9396ceba9f829b978a969fd4999597">[email protected]</a></span>
  <span id="count" class="count"></span>
</div>

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

Tips for eliminating repeated values in a textbox

<script> $("#filter").on("shown.bs.popover",function(){ $(".popover-content input[type=checkbox]").on("click",function(){ if(this.checked) { this.setAttribute("checked","checked"); } else { ...

Can you confirm if this is the most efficient method for loading google-analytics and jQuery?

It's not necessary for jQuery to be loaded immediately on page load: Here is what I currently have: <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', '...']); _gaq.pus ...

Whenever I try to access my Node.js API from Heroku's live server, I encounter a CORS policy error

Whenever I try to access my Node.js API from the Angular app (running on a local setup) and host the API on Heroku's live server, I encounter the following error: CORS policy: No 'Access-Control-Allow-Origin'. Interestingly, when I host the ...

How to toggle between checked and unchecked states using jQuery within AngularJS?

After reloading, the checkbox should maintain its checked or unchecked state. This functionality can be achieved using a directive controller. var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {}, $checkboxes = $("#c ...

Guide to retrieve the Last-Modified date using Javascript

It is common knowledge that the document.lastModified function returns a string containing the date and time when the current document was last modified. Is it possible to obtain the Last-Modified for a script? Here is an example of HTML code: ... <s ...

Send the user back to the homepage without the need to refresh the page

When the user clicks "Okay" in my window.prompt, the code below opens a new tab. Is there a way to direct the user to the home page without opening a new tab? if (window.confirm("Do you really want to leave?")) { window.open("./Tutoria ...

Having difficulty retrieving parameter data from AJAX post method in the controller

id_estado is showing up as null in the cidade controller Is the URL $.post parameter being called correctly? var base_url = "<?php echo base_url(); ?>"; $(function(){ $('#estados').change(function(){ var id_estado = $('#e ...

Adjustable div height: reduce until reaching a certain point and then begin expanding once more

Incorporating a hero section to display content is my current approach. The design adapts responsively utilizing the padding-bottom percentage strategy, along with an inner container that is absolutely positioned for central alignment of the content. The ...

Tips for combining a linear-gradient and background-image on a single element:

Is it possible to apply a linear-gradient color along with a background-image on the same div element in HTML? I've been trying to achieve this but haven't been successful so far. Any suggestions would be greatly appreciated. Below is the snippe ...

What is the best way to include query parameters in form data within a Rails link_to instead of tacking them onto the URL?

I am facing an issue with my page that displays transaction search results. I have a search filter based on the "Token" column and when clicked, the search criteria should be set, and the search params should be passed as form-data in a POST method. Howeve ...

What is the reason behind being limited to sending only 5 requests if I fail to heed the data event?

I've come across some related questions while researching this topic, such as Why is node.js only processing six requests at a time?. However, I am still struggling to fully grasp the specifics. Below is a breakdown of my scenario: Firstly, let&apos ...

Revamp the website to create a more streamlined and compact version that mirrors the functionality of the desktop website

My goal is to make my website responsive on all mobile devices. I want the mobile version to look exactly like the desktop version, just smaller in size. I attempted using transform but it didn't have the desired effect. I aim to achieve the same con ...

"Step-by-Step Guide to Dividing and Centering Text Sections with Dynamic

Initially, my intention is to implement the concept outlined below. The webpage has dual potential states. In the first scenario, two texts (with potentially varying lengths) are centralized together as a header. When transitioning to the second state, the ...

"Incorporating a hyperlink into a newly added table row with the help

When utilizing jQuery, I am able to dynamically add rows to a table with each row containing an anchor tag. However, when attempting to populate the anchor tags with links using jQuery, the links do not appear as expected. Strangely enough, the other data ...

Error: An unexpected identifier was found within the public players code, causing a SyntaxError

As a newcomer to jasmine and test cases, I am endeavoring to create test cases for my JavaScript code in fiddle. However, I'm encountering an error: Uncaught SyntaxError: Unexpected identifier Could you guide me on how to rectify this issue? Below is ...

Approach to dividing PHP output into multiple outputs (AJAX, PHP) (nested AJAX requests, AJAX inside AJAX loop?)

Seeking advice on how to efficiently handle PHP output in small chunks for AJAX responseText. The project involves a webpage using AJAX to input a last name, which is then processed by a PHP program. The PHP code randomly selects three people with differen ...

Transferring canvas element via socket with JS stack size limit

I'm encountering an issue where I need to transfer a canvas element over sockets using socket.io and Node.js. The code snippet below illustrates my approach: var myCanvas = document.getElementById("myCanvas"); var ctx = myCanvas.getContext("2d"); // ...

Is there a way to render a component without having to render AppComponent constantly?

I am looking to display two components (AppComponent and UserComponent) without constantly displaying AppComponent. Here's how my code is structured: app.routing.module.ts const routes: Routes = [ { path: '', component: AppComponent ...

The CSS code ".btn btn-primary * { visibility: hidden; } is failing to work as intended

Trying to hide specific buttons for print using CSS, but it doesn't seem to be working. Here is the code snippet: .btn btn-primary * { visibility: hidden; } <div id="control" style="display: none"> <button class="bt ...

Looking for a way to add interactivity to this canvas rectangle?

ctx.fillStyle = "#9b958c"; ctx.fillRect(sampleRectX, sampleRectY, sampleRectW, sampleRectH); ctx.fillStyle = "#fff"; ctx.fillText("Click here to play again.", sampleTextX, sampleTextY); This clickable rectangle has been giving me some trouble. While I fou ...