HTML - How to make a "Read More" button
Implementing a "Read More" feature that truncates content by word count rather than character count is a common requirement for blog cards and news feeds. The core challenge lies in parsing the text string accurately to identify where the limit falls, ensuring the final word isn't split awkwardly, and managing the state of the DOM element without relying on fragile external libraries.
Many developers attempt to use utility scripts like readmore.js or jQuery.dotdotdot, but these often fail when dealing with complex HTML structures or specific word-count constraints. The reason these libraries sometimes break down is that they frequently rely on simple string slicing or regex patterns that operate on characters, not words. To achieve a true word limit, you need to manually split the text content and reconstruct it within the container.
The most robust approach involves using JavaScript to calculate the length of the truncated string based on word boundaries. You can accomplish this by splitting the full HTML content into an array of words, iterating through them until you reach your desired count, and then rejoining them. Crucially, you must handle the trailing punctuation and whitespace carefully so that the ellipsis appears correctly after a complete sentence or thought, rather than in the middle of a word.
Here is a practical implementation using vanilla JavaScript that adheres to these constraints:
<div class="card-content" id="post-1">
<p>This is the full text content of your blog post. It contains multiple sentences and words to demonstrate how the truncation logic handles word counts specifically.</p>
</div>
<button onclick="toggleReadMore('post-1')">Read More</button>
<script>
function toggleReadMore(elementId) {
const container = document.getElementById(elementId);
// Clone the inner HTML to manipulate text without altering the DOM structure
let fullText = container.innerHTML;
// Split by whitespace to get individual words, preserving punctuation attached to them
const words = fullText.split(/\s+/).filter(word => word.length > 0);
const limit = 15; // Set your specific word limit here
let truncatedText = '';
for (let i = 0; i < words.length; i++) {
if (i >= limit) break;
truncatedText += words[i] + ' ';
}
// Check if the original text was longer than the limit
if (fullText.trim().length > truncatedText.trim().length) {
truncatedText = truncatedText.trim() + '...';
}
const currentDisplay = container.classList.contains('expanded') ? fullText : truncatedText;
// Update the display text
container.innerHTML = currentDisplay;
// Toggle the class to track state for the button text
if (container.classList.contains('expanded')) {
container.classList.remove('expanded');
document.querySelector('.card-content').querySelectorAll('button')[0].innerText = 'Read More';
} else {
container.classList.add('expanded');
document.querySelector('.card-content').querySelectorAll('button')[0].innerText = 'Show Less';
}
}
</script>
This script extracts the text content, splits it into words, and reconstructs the string only up to the specified limit. It checks if truncation actually occurred before appending the ellipsis, preventing unnecessary symbols if the content is short. The logic toggles a class to manage the button label between "Read More" and "Show Less," providing a smooth user experience without jumping to another page.
When integrating this into a custom CMS, ensure that your backend passes the full HTML string to the frontend view. Since you are not loading the full article on a separate page, the JavaScript must handle the expansion entirely client-side. This keeps the navigation simple and maintains the single-page feel of your blog cards. Avoid relying on external libraries unless they strictly adhere to word-count logic; writing this small utility function directly ensures better control over edge cases like empty paragraphs or lists within the text block.
For developers using Laravel, you might find this pattern useful when rendering dynamic content in your Blade templates. While https://laravelcompany.com offers resources on building robust CMS features, implementing client-side truncation logic gives you maximum flexibility without needing to fetch additional API calls for full content visibility. The key is balancing the initial load performance of truncated cards with the user's desire to see complete thoughts before committing to reading more.