Display the value of a shortened string

My Goal

I aim to develop a method for determining the amount of a string visible before it gets cut off.

Motivation

In my project, there is a collection of items that can be chosen. A panel presents a concatenated string of the selected item names separated by commas. If the string exceeds a certain length, it should be shortened with a +{number} indicating additional hidden selections.

Illustrative Example

https://stackblitz.com/edit/angular-ivy-cbyemy

The provided StackBlitz contains a basic demonstration of this scenario.

Current panel title:

an item, another item, som... +6

Desired outcome:

an item, another item, som... +3

Attempts So Far

  • My efforts involved using element.innerHTML and element.innerText to extract the displayed portion of the string, but they only return the full un-truncated text.

Answer №1

Utilized a solution found in this resource and made some modifications to fit the specific requirements.

Check out the updated working demo of your forked stackblitz here.

This function can be used to determine the count of visible characters -

countVisibleCharacters(element): number {
var text = element.firstChild.nodeValue;
var count = 0;

element.removeChild(element.firstChild);

for (var i = 0; i < text.length; i++) {
  var newNode = document.createElement('span');
  newNode.appendChild(document.createTextNode(text.charAt(i)));
  element.appendChild(newNode);

  if (newNode.offsetLeft < element.offsetWidth) {
    count++;
  }
}

return count;
}

You can then retrieve the suffix like this -

getTitleSuffix(): void {
let element = document.getElementById('title');
let count = this.countVisibleCharacters(element);
let substr = element.textContent;
substr = substr.substring(count - 1);
this.titleSuffix = substr.split(',').length;

}

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

Issue with the Bootstrap carousel jQuery plugin

Hi everyone, I need some help with creating a multiple items bootstrap carousel. I keep getting an error message that says "#Carousel".carousel is not a function TypeError: "#Carousel".carousel is not a function. Can anyone guide me on how to fix this issu ...

Display a list of items using ReactJS by mapping through an array of objects and rendering based on

How can I render a set of <div> </div> based on the items in an object without having to specify their names? In the code snippet below, I want the display of WorkObjectID and WorkObjectVal to be dynamic rather than static. If I include TempOb ...

The usage of uppercase letters in HTML attributes

I'm struggling to get animation working on my chart. I have been using jQuery's append function to add an animation tag to my HTML page, but for some reason the animation isn't displaying properly. The issue seems to be related to the capita ...

"Unlocking the power of Webdriver.io: Sending information to a personalized reporting system

Utilizing the wdio tool provided by the webdriver.io npm package is how I execute Mocha test-cases. The snippet below showcases a segment of the wdio.conf.js file: var htmlReporter = require('./js/reporter/htmlReporter'); htmlReporter.reporterN ...

Quiz application utilizing MySQL and JSP technology

I've been developing a Web Application using JSP to host MCQ quizzes. The questions are stored in a MySql Database table called 'qna', with each question having 10 choices. My goal is to design the quiz so that each question appears on a new ...

Issue with cutting of rotating pseudo element

Trying to rotate a pseudo element with a background-image is posing a challenge. The background, positioned at the center of the main element for visual effect, ends up being cut off when rotated. An illustrative example has been created using random imag ...

tap the hyperlink to complete the form and mimic the action of a designated

I'm working on an HTML form that includes a table and two submit buttons. <input type="image" name="button1" value="First Button" src="some_image.png"> <input type="image" name="button2" value="Second Button" src="some_image.png"> One ch ...

Adjust the positioning of a class element

I have an eye icon that changes position when clicked. Initially, it is set to left: 10%;, but if there is a DOM element with the ID login-section, it should be repositioned to left: 50%;. I attempted to use document.getElementsByClassName('fa-eye-sl ...

Guide to triggering an Observable depending on the result of a different Observable and obtaining an Observable as output

Looking to implement a service method in Angular 10 that returns an Observable for a custom User object. The goal is to have a service method that checks if the main service is running, and if not, return data from a local resource as an alternative. Pseu ...

Safari Browser does not currently offer support for MediaRecorder functionality

[Log] Webcam permission error Error: MediaRecorder is not supported I am facing an issue while trying to record audio. The Chrome browser allows audio recording without any problem, but Safari is throwing an error. global.audioStream = await navigator.m ...

Guide on passing the set[State] function to a trigger component that is not a descendent

Take a look at this diagram. ChildComponentB contains a state called stateX. In ChildComponentA, when a certain event occurs, it should modify the stateX in ChildComponentB. If ChildComponentA is a child component of ChildComponentB, passing the setStateX ...

Encountering the error "java.lang.IndexOutOfBoundsException: Index: 1, Size: 1" while attempting to choose the second option in the dropdown menu

I need to choose the third option from a drop-down list that is enclosed in a div element. However, when I try to retrieve the items in the drop-down using Selenium, the size of the drop-down list is only showing as 1 even though there are actually 10 it ...

What is the process for adding a counter variable to a field within a Twig file?

I'm working on a Twig file where I need to create a table and populate it with data using a loop. The issue is that all my field names are the same, so I want to add a counter variable to differentiate them. How can I achieve this? Below is the code ...

The scrolling feature induces a contraction to the left side

Recently, I implemented the code below to fix my menu when scrolling the page: var num = 5; $(window).bind('scroll', function () { if ($(window).scrollTop() > num) { $('.scroll').css({'position':'fixed&apo ...

Approximately 20% of spoken words are not accurately conveyed by Speech Synthesis Google Voices, failing to adhere to the intended voice selection

When using speechSynthesis.speak(utterance) in Chrome with the "Google UK English Female" voice, there is an issue where a male voice is randomly spoken instead. Any thoughts on how to resolve this? Latest Update: July 26th, 2022 This appears to be a bug ...

Utilizing Vue to Embed Multiple Hubspot Forms on one Page

While working on a Vue page, I encountered an issue with loading multiple Hubspot forms simultaneously. Only one form would load at a time. Here is the code snippet I used to append a single Hubspot form: mounted() { const script = document.createElem ...

What is the abbreviated term for personalized elements in React Native development?

After discovering that custom components can be created like this: const CustomComp=()=>{ console.log('Created custom comp'); return(<View></View>); } export default function App(){ return(<View style={{flex:1}}> &l ...

Is there a feature in impress.js that allows for navigating to the following slide easily?

Impress.js is an innovative web presentation tool created with Javascript. I am interested in setting up custom events to navigate through the slides. This could involve adding buttons for "Next" and "Previous", for example. The impress.js file itself fun ...

How come my JavaScript regular expression doesn't function properly when applied to elements in an array?

let numbers = new Array('1','2','3'); let letters = new Array('a','b','c'); let length = numbers.length; let str = 'abcdefgabcdefg'; for (let i=0; i<length; i++) { let regex = new ...

Extracting a compilation of video content from a YouTube channel through JSON data retrieval

I'm struggling to display the 5 most recent videos (title, updated, thumbnail (hqDefault)) from a specific channel using JSON data. I've tried various guides but can't seem to parse it correctly. Any suggestions on how to achieve this? I&apo ...