25% off ProSNIPC25OFF

Read More / Read Less Toggle

Collapses long text blocks to a configurable height and adds a Read More / Read Less button that smoothly expands and collapses the content.

JavaScriptby SnipCraft
js
(function () {
  'use strict';

  document.addEventListener('DOMContentLoaded', function () {
    var containers = document.querySelectorAll('[data-readmore]');
    if (!containers.length) { return; }

    containers.forEach(function (el) {
      var maxHeight = parseInt(el.getAttribute('data-readmore') || '120', 10);
      var moreLabel = el.getAttribute('data-more-label') || 'Read More';
      var lessLabel = el.getAttribute('data-less-label') || 'Read Less';

      // Only collapse if content is taller than the max height
      if (el.scrollHeight <= maxHeight) { return; }

      el.style.overflow   = 'hidden';
      el.style.maxHeight  = maxHeight + 'px';
      el.style.transition = 'max-height 0.35s ease';

      var btn = document.createElement('button');
      btn.type      = 'button';
      btn.textContent = moreLabel;
      btn.style.cssText = [
        'display:inline-block',
        'margin-top:8px',
        'background:none',
        'border:none',
        'padding:0',
        'cursor:pointer',
        'font:inherit',
        'text-decoration:underline',
        'color:inherit',
      ].join(';') + ';';

      el.parentNode.insertBefore(btn, el.nextSibling);

      var expanded = false;
      btn.addEventListener('click', function () {
        expanded            = !expanded;
        el.style.maxHeight  = expanded ? el.scrollHeight + 'px' : maxHeight + 'px';
        btn.textContent     = expanded ? lessLabel : moreLabel;
      });
    });
  });
}());
#accessibility#content#display#toggle#ux