In Webflow, you can truncate the length of a text or title while preserving readability by utilizing the native JavaScript method and applying it to elements with a specific class, such as ".longtrend."
Here's an example of a native JavaScript solution that truncates text while avoiding word truncation:
```javascript
// Select all elements with class ".longtrend"
const elements = document.querySelectorAll('.longtrend');
// Function to truncate text
function truncateText(element, maxLength) {
const truncatedText = element.textContent.trim().substring(0, maxLength);
const lastSpaceIndex = truncatedText.lastIndexOf(' ');
if (lastSpaceIndex !== -1) {
element.textContent = truncatedText.substring(0, lastSpaceIndex) + '...';
} else {
element.textContent = truncatedText + '...';
}
}
// Loop through each element and truncate text
elements.forEach(element => {
// Set the desired maximum length of the text
const maxLength = 50;
truncateText(element, maxLength);
});
```
This script selects all elements with the class ".longtrend" using `querySelectorAll()`. Then, a separate function called `truncateText()` is defined, which takes an element and a maxLength as parameters. The function trims the text content of the element and truncates it to the desired maxLength.
To avoid word truncation, the function finds the last occurrence of a space character within the truncatedText and slices the string accordingly. If no space is found, the ellipsis '...' is added directly to the truncated text.
Finally, the script loops through each element with the ".longtrend" class and calls the `truncateText()` function, passing the element and the desired maxLength.
To use this script in Webflow, follow these steps:
1. In the Webflow Designer, select the page where your ".longtrend" elements are located.
2. In the Page Settings panel, choose the "Before
" option.
3. Click on the "" to open the Code Embed modal.
4. Paste the JavaScript code within a `