JAVASCRIPT

Implement a Dynamic 'Read More/Read Less' Text Expander

Learn how to create a JavaScript function to dynamically truncate long text content and provide a 'Read More/Read Less' toggle button for better user experience.

function createTextExpander(elementId, maxLength) {
  const element = document.getElementById(elementId);
  if (!element) {
    console.error(`Element with ID '${elementId}' not found.`);
    return;
  }

  const originalText = element.textContent.trim();
  if (originalText.length <= maxLength) {
    return; // No need to expand/collapse
  }

  const shortText = originalText.substring(0, maxLength);
  let isExpanded = false;

  const expanderButton = document.createElement('button');
  expanderButton.textContent = 'Read More';
  expanderButton.style.cssText = 'background: none; border: none; color: blue; cursor: pointer; text-decoration: underline; padding: 0; font: inherit;';

  const updateText = () => {
    element.textContent = isExpanded ? originalText : shortText + '...';
    expanderButton.textContent = isExpanded ? 'Read Less' : 'Read More';
  };

  expanderButton.addEventListener('click', () => {
    isExpanded = !isExpanded;
    updateText();
  });

  // Initial setup
  element.textContent = shortText + '...';
  element.parentNode.insertBefore(expanderButton, element.nextSibling); // Insert after the element
}

// Usage example:
// <p id="myLongText">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
// createTextExpander('myLongText', 150);
How it works: This snippet creates a 'Read More/Read Less' functionality for a given text element. It truncates the text to a specified maximum length, appends an ellipsis, and adds a button. Clicking the button toggles between the full and truncated text, dynamically updating the content and button label, improving readability for long articles.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs