Skip to content
Advertisement

How to clamp/unclamp blocks of text in jQuery or Vanilla JS?

I can’t figure out how to do the following in jQuery or Vanilla JS.

For the layout below I want to do the following:

  1. Compress each text block using multi-clamp library to three (3) lines.
  2. When you click on the “Read more” button or on the block itself, that block of text should “expand” (unclamp) completely.

"use strict";!function(t,e){"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?module.exports=e():t.MultiClamp=t.MultiClamp||e()}(this,function(){function a(t){return parseInt(t,10)}function l(t){return(t+"").replace(/[^d.]/g,"")-0}function h(t){return Math.round(100*t)/100}function m(t,e){return"textContent"in t?t.textContent=e:t.innerText=e}function o(t,e){return window.getComputedStyle?window.getComputedStyle(t,null).getPropertyValue(e):t.currentStyle.getAttribute(e.replace(/-(w)/g,function(t,e){return e.toUpperCase()}))}function c(t){var e=o(t,"height");return-1<e.indexOf("px")?l(e):h(l(t.clientHeight)-l(o(t,"padding-top"))-l(o(t,"padding-bottom")))}var t=function(t,e){t&&(this.element=t.length?t[0]:t,this.originalOption=e||{},this.originalElement=this.element.cloneNode(!0),this.preInit(this.originalOption),this.init())};return t.prototype={constructor:t,reload:function(t){if(t){if(t.useOriginalText&&(this.element.innerHTML=this.originalElement.innerHTML),"-webkit-box"===this.element.style.display)for(var e=["display","overflow","WebkitLineClamp","WebkitBoxOrient"],i=0;i<e.length;i++)this.element.style[e[i]]=this.originalElement.style[e[i]];var n={};for(var l in this.originalOption)n[l]=this.originalOption[l];for(var o in t)n[o]=t[o];this.preInit(n)}this.init()},preInit:function(t){if(this.option={ellipsis:"ellipsis"in t?t.ellipsis:"...",clamp:"clamp"in t?t.clamp:3,reverse:"reverse"in t&&!!t.reverse,splitByWords:"splitByWords"in t&&!!t.splitByWords,disableCssClamp:"disableCssClamp"in t&&!!t.disableCssClamp,onClampStart:"onClampStart"in t&&"function"==typeof t.onClampStart?t.onClampStart:function(){},onClampEnd:"onClampEnd"in t&&"function"==typeof t.onClampEnd?t.onClampEnd:function(){}},"lineTextLen"in t&&(this.option.lineTextLen=t.lineTextLen),"auto"===this.option.clamp)this.autoClamp=!0;else{if(this.option.clamp=a(this.option.clamp),isNaN(this.option.clamp)||this.option.clamp<1)throw new Error("Invaild clamp number!");this.autoClamp=!1}this.useCssClamp=!(this.option.disableCssClamp||this.autoClamp||this.option.reverse||this.option.splitByWords||"..."!==this.option.ellipsis||void 0===document.body.style.webkitLineClamp)},init:function(){if(this.useCssClamp){var t={display:"-webkit-box",overflow:"hidden",WebkitLineClamp:this.option.clamp,WebkitBoxOrient:"vertical"};for(var e in t)this.element.style[e]=t[e]}else this.contentText="textContent"in(i=this.element)?i.textContent:i.innerText,this.ellipsis=function(t){if(/^<[wW]+>$/.test(t)){var e=document.createElement("div");return e.innerHTML=t,e.firstElementChild||e.firstChild}return t}(this.option.ellipsis),this.clamp();var i},getSingleLineHeight:function(){var t=o(this.element,"line-height"),i=this;if(-1<t.indexOf("px"))return l(t);if(isNaN(t))return n();var e=o(this.element,"font-size");return-1<e.indexOf("px")?h(l(e)*t):-1<e.indexOf("pt")?h(4*l(e)/3*t):n();function n(){var t=i.element.innerHTML;i.element.innerHTML=".";var e=c(i.element);return i.element.innerHTML=t,e}},clamp:function(){var t,e,i,n,l=this;if(t=this.getSingleLineHeight(),""!==this.contentText&&t){if(this.autoClamp?(i=c(this.element),this.option.clamp=a(i/t),n=this.element.style.height,this.element.style.height="auto"):i=h(t*this.option.clamp),!(e=c(this.element))||!i||e<=i)return this.autoClamp&&(this.element.style.height=n),void p();var o=this.option.onClampStart.call(this,{needClamp:!0});if(void 0===o||o){var s=this.option.splitByWords?this.contentText.match(/w+|W+?/g):this.contentText,r=a(this.option.lineTextLen||Math.min(20,this.contentText.length/this.option.clamp))*this.option.clamp;this.trunkSlice(s,i,r,r,!1),this.autoClamp&&(this.element.style.height=n),this.option.onClampEnd.call(this,{didClamp:!0})}else this.autoClamp&&(this.element.style.height=n),p(!0)}else p();function p(t){t||l.option.onClampStart.call(l,{needClamp:!1}),l.option.onClampEnd.call(l,{didClamp:!1})}},trunkSlice:function(t,e,i,n,l){var o,s=this,r=this.option.reverse?t.slice(t.length-n):t.slice(0,n);if(p(this.option.splitByWords?r.join(""):r),c(this.element)>e)o=l?i:a(i/2)||1,this.trunkSlice(t,e,o,n-o,!0);else{if(1===i&&l)return void(this.option.splitByWords&&/s/.test(r[this.option.reverse?0:r.length-1])?p((this.option.reverse?r.slice(1):r.slice(0,r.length-1)).join(""),!0):p(this.option.splitByWords?r.join(""):r,!0));o=l?a(i/2)||1:i,this.trunkSlice(t,e,o,n+o,!1)}function p(t,e){"object"==typeof s.ellipsis?(m(s.element,t),s.option.reverse?s.element.insertBefore(e?s.ellipsis:s.ellipsis.cloneNode(!0),s.element.firstChild):s.element.appendChild(e?s.ellipsis:s.ellipsis.cloneNode(!0))):s.option.reverse?m(s.element,s.ellipsis+t):m(s.element,t+s.ellipsis)}}},t});

$("#info .descr").each(function(i, obj) {
    new MultiClamp(obj, {
        ellipsis: '...',
        clamp: 3
    });
});
* {
  margin: 0;
  padding: 0;
}

.container {
  max-width: 480px;
  margin: 10px auto;
  padding: 0;
  width: 100%;
}

.container:after,
.container:before {
  display: table;
  content: " ";
}

.row {
  margin-bottom: 10px;
}

.row:after {
  content: '';
  display: block;
  height: 0;
  clear: both;
}

.col {
  display: inline;
  float: left;
  margin: 0 5px;
  width: 100%;
  max-width: 150px;
  text-align: left;
}

a {
  color: #000000;
  text-decoration: none;
}

.wrap {
  position: relative;
  min-height: 100%;
  padding: 10px 10px 10px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  background-color: yellow;
}

h3 {
  margin-bottom: 10px;
}

.btn {
  margin-top: 10px;
  background-color: #000000;
  color: #ffffff;
  display: inline-block;
  padding: 5px 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>^
<div id="info" class="container">
  <div class="row">
    <div class="col">
      <a href="#">
        <div class="wrap">
          <h3>Heading 1</h3>
          <div class="descr">
            Lorem ipsum dolor sit amet<br />
            Morbi hendrerit justo non<br />
            Mauris et ligula efficitur<br />
            Suspendisse eget nulla lobortis<br />
            Proin vel quam ornare, commodo sem<br />
            Suspendisse luctus nisi nec<br />
            Nullam volutpat mi ut metus rutrum<br />
            Fusce vehicula ipsum in mauris<br />
            Suspendisse consequat leo
          </div>
          <div class="btn">
            Read More
          </div>
        </div>
      </a>
    </div>
    <div class="col">
      <a href="#">
        <div class="wrap">
          <h3>Heading 2</h3>
          <div class="descr">
            Lorem ipsum dolor sit amet<br />
            Morbi hendrerit justo non<br />
            Mauris et ligula efficitur<br />
            Suspendisse eget nulla lobortis
          </div>
          <div class="btn">
            Read More
          </div>
        </div>
      </a>
    </div>
    <div class="col">
      <a href="#">
        <div class="wrap">
          <h3>Heading 3</h3>
          <div class="descr">
            Lorem ipsum dolor sit amet<br />
            Morbi hendrerit justo non<br />
            Mauris et ligula efficitur<br />
            Suspendisse eget nulla lobortis<br />
            Proin vel quam ornare, commodo sem<br />
            Suspendisse luctus nisi nec<br />
            Nullam volutpat mi ut metus rutrum<br />
            Fusce vehicula ipsum in mauris
          </div>
          <div class="btn">
            Read More
          </div>
        </div>
      </a>
    </div>
  </div>
  <div class="row">
    <div class="col">
      <a href="#">
        <div class="wrap">
          <h3>Heading 4</h3>
          <div class="descr">
            Lorem ipsum dolor sit amet<br />
            Morbi hendrerit justo non<br />
            Mauris et ligula efficitur<br />
            Suspendisse eget nulla lobortis<br />
            Proin vel quam ornare, commodo sem
          </div>
          <div class="btn">
            Read More
          </div>
        </div>
      </a>
    </div>
    <div class="col">
      <a href="#">
        <div class="wrap">
          <h3>Heading 5</h3>
          <div class="descr">
            Lorem ipsum dolor sit amet<br />
            Morbi hendrerit justo non<br />
            Mauris et ligula efficitur<br />
            Suspendisse eget nulla lobortis<br />
            Proin vel quam ornare, commodo sem<br />
            Suspendisse luctus nisi nec<br />
            Nullam volutpat mi ut metus rutrum<br />
            Fusce vehicula ipsum in mauris
          </div>
          <div class="btn">
            Read More
          </div>
        </div>
      </a>
    </div>
    <div class="col">
      <a href="#">
        <div class="wrap">
          <h3>Heading 6</h3>
          <div class="descr">
            Lorem ipsum dolor sit amet<br />
            Morbi hendrerit justo non<br />
            Mauris et ligula efficitur
          </div>
          <div class="btn">
            Read More
          </div>
        </div>
      </a>
    </div>
  </div>
</div>

So far I’ve only figured out how to compress each block to three lines:

$("#info .descr").each(function(i, obj) {
    new MultiClamp(obj, {
        ellipsis: '...',
        clamp: 3
    });
});

Advertisement

Answer

You can use the reload(options) method to achieve this.

reload(options)

You can change initial options when reloading through the options param, and use the original text to re-clamp when options.useOriginalText set to true. default: { …initOptions, useOriginalText: false }

Try this

"use strict";!function(t,e){"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?module.exports=e():t.MultiClamp=t.MultiClamp||e()}(this,function(){function a(t){return parseInt(t,10)}function l(t){return(t+"").replace(/[^d.]/g,"")-0}function h(t){return Math.round(100*t)/100}function m(t,e){return"textContent"in t?t.textContent=e:t.innerText=e}function o(t,e){return window.getComputedStyle?window.getComputedStyle(t,null).getPropertyValue(e):t.currentStyle.getAttribute(e.replace(/-(w)/g,function(t,e){return e.toUpperCase()}))}function c(t){var e=o(t,"height");return-1<e.indexOf("px")?l(e):h(l(t.clientHeight)-l(o(t,"padding-top"))-l(o(t,"padding-bottom")))}var t=function(t,e){t&&(this.element=t.length?t[0]:t,this.originalOption=e||{},this.originalElement=this.element.cloneNode(!0),this.preInit(this.originalOption),this.init())};return t.prototype={constructor:t,reload:function(t){if(t){if(t.useOriginalText&&(this.element.innerHTML=this.originalElement.innerHTML),"-webkit-box"===this.element.style.display)for(var e=["display","overflow","WebkitLineClamp","WebkitBoxOrient"],i=0;i<e.length;i++)this.element.style[e[i]]=this.originalElement.style[e[i]];var n={};for(var l in this.originalOption)n[l]=this.originalOption[l];for(var o in t)n[o]=t[o];this.preInit(n)}this.init()},preInit:function(t){if(this.option={ellipsis:"ellipsis"in t?t.ellipsis:"...",clamp:"clamp"in t?t.clamp:3,reverse:"reverse"in t&&!!t.reverse,splitByWords:"splitByWords"in t&&!!t.splitByWords,disableCssClamp:"disableCssClamp"in t&&!!t.disableCssClamp,onClampStart:"onClampStart"in t&&"function"==typeof t.onClampStart?t.onClampStart:function(){},onClampEnd:"onClampEnd"in t&&"function"==typeof t.onClampEnd?t.onClampEnd:function(){}},"lineTextLen"in t&&(this.option.lineTextLen=t.lineTextLen),"auto"===this.option.clamp)this.autoClamp=!0;else{if(this.option.clamp=a(this.option.clamp),isNaN(this.option.clamp)||this.option.clamp<1)throw new Error("Invaild clamp number!");this.autoClamp=!1}this.useCssClamp=!(this.option.disableCssClamp||this.autoClamp||this.option.reverse||this.option.splitByWords||"..."!==this.option.ellipsis||void 0===document.body.style.webkitLineClamp)},init:function(){if(this.useCssClamp){var t={display:"-webkit-box",overflow:"hidden",WebkitLineClamp:this.option.clamp,WebkitBoxOrient:"vertical"};for(var e in t)this.element.style[e]=t[e]}else this.contentText="textContent"in(i=this.element)?i.textContent:i.innerText,this.ellipsis=function(t){if(/^<[wW]+>$/.test(t)){var e=document.createElement("div");return e.innerHTML=t,e.firstElementChild||e.firstChild}return t}(this.option.ellipsis),this.clamp();var i},getSingleLineHeight:function(){var t=o(this.element,"line-height"),i=this;if(-1<t.indexOf("px"))return l(t);if(isNaN(t))return n();var e=o(this.element,"font-size");return-1<e.indexOf("px")?h(l(e)*t):-1<e.indexOf("pt")?h(4*l(e)/3*t):n();function n(){var t=i.element.innerHTML;i.element.innerHTML=".";var e=c(i.element);return i.element.innerHTML=t,e}},clamp:function(){var t,e,i,n,l=this;if(t=this.getSingleLineHeight(),""!==this.contentText&&t){if(this.autoClamp?(i=c(this.element),this.option.clamp=a(i/t),n=this.element.style.height,this.element.style.height="auto"):i=h(t*this.option.clamp),!(e=c(this.element))||!i||e<=i)return this.autoClamp&&(this.element.style.height=n),void p();var o=this.option.onClampStart.call(this,{needClamp:!0});if(void 0===o||o){var s=this.option.splitByWords?this.contentText.match(/w+|W+?/g):this.contentText,r=a(this.option.lineTextLen||Math.min(20,this.contentText.length/this.option.clamp))*this.option.clamp;this.trunkSlice(s,i,r,r,!1),this.autoClamp&&(this.element.style.height=n),this.option.onClampEnd.call(this,{didClamp:!0})}else this.autoClamp&&(this.element.style.height=n),p(!0)}else p();function p(t){t||l.option.onClampStart.call(l,{needClamp:!1}),l.option.onClampEnd.call(l,{didClamp:!1})}},trunkSlice:function(t,e,i,n,l){var o,s=this,r=this.option.reverse?t.slice(t.length-n):t.slice(0,n);if(p(this.option.splitByWords?r.join(""):r),c(this.element)>e)o=l?i:a(i/2)||1,this.trunkSlice(t,e,o,n-o,!0);else{if(1===i&&l)return void(this.option.splitByWords&&/s/.test(r[this.option.reverse?0:r.length-1])?p((this.option.reverse?r.slice(1):r.slice(0,r.length-1)).join(""),!0):p(this.option.splitByWords?r.join(""):r,!0));o=l?a(i/2)||1:i,this.trunkSlice(t,e,o,n+o,!1)}function p(t,e){"object"==typeof s.ellipsis?(m(s.element,t),s.option.reverse?s.element.insertBefore(e?s.ellipsis:s.ellipsis.cloneNode(!0),s.element.firstChild):s.element.appendChild(e?s.ellipsis:s.ellipsis.cloneNode(!0))):s.option.reverse?m(s.element,s.ellipsis+t):m(s.element,t+s.ellipsis)}}},t});

document.querySelectorAll("#info .descr").forEach(el => {
    let instance = new MultiClamp(el, {
        ellipsis: '...',
        clamp: 3
    });

    let a = el.closest('a');
    a.addEventListener('click', e => {
        e.preventDefault();
        instance.reload({clamp: 40000});
        a.querySelector('.btn').style.display = 'none';
    }, { once: true })
})
* {
  margin: 0;
  padding: 0;
}

.container {
  max-width: 480px;
  margin: 10px auto;
  padding: 0;
  width: 100%;
}

.container:after,
.container:before {
  display: table;
  content: " ";
}

.row {
  margin-bottom: 10px;
}

.row:after {
  content: '';
  display: block;
  height: 0;
  clear: both;
}

.col {
  display: inline;
  float: left;
  margin: 0 5px;
  width: 100%;
  max-width: 150px;
  text-align: left;
}

a {
  color: #000000;
  text-decoration: none;
}

.wrap {
  position: relative;
  min-height: 100%;
  padding: 10px 10px 10px;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
  background-color: yellow;
}

h3 {
  margin-bottom: 10px;
}

.btn {
  margin-top: 10px;
  background-color: #000000;
  color: #ffffff;
  display: inline-block;
  padding: 5px 10px;
}
<div id="info" class="container">
  <div class="row">
    <div class="col">
      <a href="#">
        <div class="wrap">
          <h3>Heading 1</h3>
          <div class="descr">
            Lorem ipsum dolor sit amet<br /> Morbi hendrerit justo non<br /> Mauris et ligula efficitur<br /> Suspendisse eget nulla lobortis<br /> Proin vel quam ornare, commodo sem<br /> Suspendisse luctus nisi nec<br /> Nullam volutpat mi ut metus
            rutrum<br /> Fusce vehicula ipsum in mauris<br /> Suspendisse consequat leo
          </div>
          <div class="btn">
            Read More
          </div>
        </div>
      </a>
    </div>
    <div class="col">
      <a href="#">
        <div class="wrap">
          <h3>Heading 2</h3>
          <div class="descr">
            Lorem ipsum dolor sit amet<br /> Morbi hendrerit justo non<br /> Mauris et ligula efficitur<br /> Suspendisse eget nulla lobortis
          </div>
          <div class="btn">
            Read More
          </div>
        </div>
      </a>
    </div>
    <div class="col">
      <a href="#">
        <div class="wrap">
          <h3>Heading 3</h3>
          <div class="descr">
            Lorem ipsum dolor sit amet<br /> Morbi hendrerit justo non<br /> Mauris et ligula efficitur<br /> Suspendisse eget nulla lobortis<br /> Proin vel quam ornare, commodo sem<br /> Suspendisse luctus nisi nec<br /> Nullam volutpat mi ut metus
            rutrum<br /> Fusce vehicula ipsum in mauris
          </div>
          <div class="btn">
            Read More
          </div>
        </div>
      </a>
    </div>
  </div>
  <div class="row">
    <div class="col">
      <a href="#">
        <div class="wrap">
          <h3>Heading 4</h3>
          <div class="descr">
            Lorem ipsum dolor sit amet<br /> Morbi hendrerit justo non<br /> Mauris et ligula efficitur<br /> Suspendisse eget nulla lobortis<br /> Proin vel quam ornare, commodo sem
          </div>
          <div class="btn">
            Read More
          </div>
        </div>
      </a>
    </div>
    <div class="col">
      <a href="#">
        <div class="wrap">
          <h3>Heading 5</h3>
          <div class="descr">
            Lorem ipsum dolor sit amet<br /> Morbi hendrerit justo non<br /> Mauris et ligula efficitur<br /> Suspendisse eget nulla lobortis<br /> Proin vel quam ornare, commodo sem<br /> Suspendisse luctus nisi nec<br /> Nullam volutpat mi ut metus
            rutrum<br /> Fusce vehicula ipsum in mauris
          </div>
          <div class="btn">
            Read More
          </div>
        </div>
      </a>
    </div>
    <div class="col">
      <a href="#">
        <div class="wrap">
          <h3>Heading 6</h3>
          <div class="descr">
            Lorem ipsum dolor sit amet<br /> Morbi hendrerit justo non<br /> Mauris et ligula efficitur
          </div>
          <div class="btn">
            Read More
          </div>
        </div>
      </a>
    </div>
  </div>
</div>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement