Instructions on how to implement a readmore button for texts that exceed a specific character length

I am attempting to display a "Read more" button if the length of a comment exceeds 80 characters. This is how I am checking it:

<tr repeat.for="m of comments">
<td if.bind="showLess">${m.comment.length < 80 ? m.comment : m.comment.substr(0,80) + " ... "}</td>
</tr>

So if the length is greater than 80, it shows the "..." at the end of the text.

However, I wanted to add a button after the dots, so I attempted this:

<td if.bind="showLess">${m.comment.length < 80 ? m.comment : m.comment.substr(0,80) + " ...<button>Read More</button> "}</td>

But this disrupted my HTML structure and displayed incorrectly as shown in the image below:

https://i.stack.imgur.com/DVZPn.png

How can I correctly structure the HTML within ${this function}? I cannot place the button outside the $ { } because it will appear even when the character count is less than 80.

Note: I opted not to use ellipsis as I require the exact character length.

Answer №1

Uncertain if this method will prove beneficial, as the utilization of character length may not be ideal in this scenario due to varying widths:

iiiiiiiiiiiiiiiiiiii...

mmmmmmmmmmmmmmmmmmmm...

Although both lines consist of 20 characters, their width differs significantly (unless a font with similar character widths is employed).

I recommend utilizing CSS to clip lines according to requirements using the following code snippet:

display: '-webkit-box',
'-webkit-line-clamp': <number of lines>,
'-webkit-box-orient': 'vertical',
overflow: 'hidden',

Substitute number of lines with the actual number of lines within that specific div.

To adjust for more or less content, consider implementing a span tag instead of a button, positioning it absolutely and situating it after the text.

Answer №2

When using Aurelia, the if.bind attribute serves as a condition to determine whether or not the tag and its contents should be visible. Essentially, it follows this logic: 'If showLess is true, then display this tag along with its contents.'

It appears that your objective is to truncate the string and add an ellipsis if it exceeds 80 characters in length.

While my familiarity with Aurelia may be a bit rusty, here's a suggestion on how you can achieve this:

<td>${m.comment.length < 80 ? m.comment : m.comment.substr(0,80)} <a if.bind=`${m.comment.length > 80}` href=# click.delegate="someFunc()">...</a></td>

To summarize, this solution will trim the string if it surpasses 80 characters and display an ellipsis accordingly. Additionally, I recommend avoiding unnecessary buttons as they may disrupt the visual appeal of your design.

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

Congratulations! Your product has been successfully added to Magento using Ajax

While using Firebug, I discovered that JSON generates a message within the success function. However, I am having trouble figuring out how to display it. As a workaround, I attempted to add the following code snippet: if(data.status == 'ERROR'){ ...

Unit test: Using subjects instead of observables to mock a service and test the change of values over time results in TypeScript throwing error TS2339

I have a unique scenario where I have implemented a service that accesses ngrx selectors and a component that utilizes this service by injecting it and adjusting properties based on the values retrieved. For unit testing purposes, I am creating mock versi ...

Managing images in JavaScript while conserving memory

Welcome I am embarking on a project to construct a webpage using HTML, CSS, JavaScript (jQuery), and nearly 1000 images. The length of the HTML page is substantial, around 5000px. My vision involves creating a captivating visual experience for users as t ...

Naming convention for TypeScript accessors

Expanding on the previous solution When I convert the example object to JSON from the answer above: JSON.stringify(obj) The output is: {"_id":"3457"} If I intend to transmit this data over a service and store it in a database, I prefer not to use the ...

Toggle the visibility of HTML elements by utilizing a JavaScript checkbox event

I have put together these JavaScript functions to hide the delivery address fields on my shopping cart address form if the goods are being sent to the billing address. The functions control the visibility of the HTML wrapped by... function getItem(id) { ...

Modify color of chosen item using button event in material ui list

My sidebar contains buttons, and when I click on a button, I want to change its color to indicate it’s selected. However, the color change doesn't always work as expected, sometimes requiring two clicks for it to take effect. Additionally, despite u ...

The module named "tapable" does not contain an export for the item "Tapable"

While developing a WordPress plugin for a custom Gutenberg block, I encountered a challenge. I needed to incorporate additional scripts in TypeScript and opted to use "$ tsc --watch" along with a "tsconfig.json" file for compilation. Upon installing @word ...

When working with React JS and the react-select library, I am looking to automatically reset the options to their default value once

I am attempting to disable the select list after unchecking the checkbox and resetting the select value back to default, but currently it is retaining the last selected option. I am utilizing React-select for the select and options in this scenario. APP.j ...

DotLottie file loading issues

While using dotlottie/react-player, webpack 4, and react 16, I encountered module parse failed errors during compilation. "@dotlottie/react-player": "^1.6.5" "webpack": "^4.44.2", "react": "16.14.0&qu ...

What is causing the delay in retrieving elements using getX() method in Selenium?

Recently, I've been experimenting with web scraping using Selenium. However, I've noticed that there is a delay when calling getText(), getAttribute(), or getTagName() on the WebElements stored in an ArrayList from the website. The website I&apo ...

best method for embedding javascript code within html (within a script tag)

In my quest to create dynamic HTML using jQuery and insert it into a specific div on my website, I encountered an issue. Specifically, I am attempting to generate an anchor element where both the href and label are determined by JavaScript variables. Here ...

Error: The function jQuery(...).hexColorPicker does not exist

I am attempting to utilize a color-picker jQuery plugin. Below is a screenshot of the JavaScript file: https://i.stack.imgur.com/ovRjx.png Here is the code I am using to initialize it: <script type="text/javascript> jQuery(function(){ ...

Can express middleware be tailored for each individual handler within the same route path?

I am seeking to create distinct routes under an /api path with varying middleware handlers, each allowing for different authentication methods. My initial approach was to nest these API routes under separate instances of the Router object using Express: c ...

Troubleshooting issue with jQuery datepicker not triggering onselect event

Query Function: $(function() { $("#iDate").datepicker({ dateFormat: 'dd MM yy', beforeShowDay: unavailable onSelect: function (dateText, inst) { $('#frmDate').submit(); } }); }); HTML ...

What steps should I follow to create an automatic image slider using Fancybox that transitions to the next slide seamlessly?

*I've recently ventured into web design and am currently experimenting with Fancybox. I'm interested in creating a slider with 3 images that automatically transitions to the next image, similar to what is seen on this website: Is it feasible to ...

The function grunt.task.run() is malfunctioning

Currently, I am experimenting with integrating Grunt into my Express application. Here is a snippet of the code I have: var grunt = require('grunt'); require(process.cwd() + '/gruntfile.js')(grunt); grunt.task.run('development&ap ...

Guide to Implementing a Single Trigger Click with jQuery for Window Scrolling

I have implemented JavaScript code for a button that loads additional posts from the database. The button has the class of .getmore. My goal now is to enable infinite scroll so that users do not have to manually click the button. In order to achieve this ...

javascript extract data from JSON

How can I extract values from the [object Object] in javascript? I have a JSON response from PHP that I am passing into JavaScript. I want to retrieve the GPSPoint_lat and GPSPoint_lon values. var jArray = ; var obj = JSON.parse(jArray); I am gett ...

How can you animate the background of a website using AngularJS - CSS or JavaScript?

My aim is to create a dynamic animation for the background image when the view changes. The current background image is set through a function defined within MainController: // app/js/controllers.js $scope.getBg = function() { return $route.current.sco ...

Determine if a MySQL query in node.js returns no results

I'm trying to determine if there are no matching results in MySQL using Node.js. How can I achieve this? mysql.query("select * from table1 where name = 'abcd'", function(error, result, field) { if(error) { handleNoError(error); ...