Is there a recommended native JS script (or jQuery or similar) for truncating the length of a text/title while preserving readability by avoiding word truncation, and is it possible to apply this to any H3 title with the class ".longtrend" in Webflow?

TL;DR
  • Use a JavaScript script within Webflow for H3 titles with the ".longtrend" class to truncate text without cutting words, and add it under the Custom Code tab in Project Settings.
  • Adjust the character limit in the script as needed, apply the ".longtrend" class to your H3 titles, and publish your Webflow site to implement the changes.

To truncate text while preserving readability by avoiding word truncation, you can use a JavaScript solution that works with Webflow elements. Here's how you can achieve this for H3 titles with the class ".longtrend":

1. Choose a Truncation Script

  • There are several JavaScript libraries available for text truncation. One popular option is dotdotdot. However, you can achieve similar results with a custom script.
  • If using jQuery, make sure jQuery is loaded on your page.

2. Add the Script to Webflow

  • Go to Project Settings and navigate to the Custom Code tab.
  • Add the following script inside the before </body> tag section:

  

<script>
document.addEventListener("DOMContentLoaded", function() {
  const textElements = document.querySelectorAll('.longtrend');

  textElements.forEach(function(element) {
    let text = element.textContent;
    let truncatedText = truncateText(text, 100); // limit to 100 characters or adjust as needed
    element.textContent = truncatedText;
  });

  function truncateText(text, limit) {
    if (text.length > limit) {
      const shortText = text.substring(0, limit).split(' ');
      shortText.pop(); // remove the last word to avoid incomplete word
      return shortText.join(' ') + '…';
    }
    return text;
  }
});
</script>

3. Publish Changes

  • Publish your Webflow site to see the changes take effect.
  • Ensure that the ".longtrend" class is properly applied to your H3 titles.

Summary

To truncate text for H3 titles with the ".longtrend" class in Webflow, use the above script to avoid truncating in the middle of a word. Adjust the character limit as necessary, and ensure your project settings are set up to include the script.

Rate this answer

Other Webflow Questions